有没有更好的方法通过google-api从gmail获取完整消息 [英] Is there any nicer way to get the full message from gmail with google-api

查看:56
本文介绍了有没有更好的方法通过google-api从gmail获取完整消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,除其他外,我需要从我的Google帐户阅读电子邮件中的消息.我想出了一个可行的解决方案,但想知道是否有任何更简单的方法?

I'm working on a project where I, among other things, need to read the message in e-mails from my google account. I came up with a solution that works but wonder if there are any simpler ways?

代码的第一部分非常标准,可以访问邮箱.但是我发布了它,以便您可以看到我为使它起作用而做了些什么.

The first part of the code is pretty standard to get access to the mailbox. But I post it so you can see what I did to get it to work.

SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET ='A.json'
store =file.Storage('storage.json')
credz=store.get()
flags = tools.argparser.parse_args(args=[])
if not credz or credz.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET,SCOPES)
    if flags:
        credz = tools.run_flow(flow, store, flags)

GMAIL = build('gmail','v1',http=credz.authorize(Http()))
response = GMAIL.users().messages().list(userId='me',q='').execute()
messages = []
if 'messages' in response:
    messages.extend(response['messages'])
print len(messages)
while 'nextPageToken' in response:
    page_token = response['nextPageToken']
    response = service.users().messages().list(userId='me', q=query,pageToken=page_token).execute()
    messages.extend(response['messages'])

FromMeInd=0
for message in messages:
    ReadMessage(GMAIL,'me',message['id'])

这是我更感兴趣的部分.还有其他方法可以更直接地使用python和gmail-api获取消息.我浏览了api文档,但无法获得更有效的阅读方式.

It is this part that I'm more interested to imporve. Is there any other way to more directly get the message with python and the gmail-api. I've looked through the api documentation but could not get any more efficient way to read it.

def ReadMessage(service,userID,messID):
    message = service.users().messages().get(userId=userID, id=messID,format='full').execute()
    decoded=base64.urlsafe_b64decode(message['payload']['body']['data'].encode('ASCII'))
    print decoded

推荐答案

您可以将主体获取为raw,然后使用标准Python

You can get the body as raw and then parse it using the standard Python email module

根据官方API: https://developers .google.com/gmail/api/v1/reference/users/messages/get :

import email

message = service.users().messages().get(userId='me', id=msg_id,
                                         format='raw').execute()

print 'Message snippet: %s' % message['snippet']

msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

mime_msg = email.message_from_string(msg_str)

您会收到一个包含的mime消息,其中包含mime部分,例如纯文本,HTML,带引号的可打印内容,附件等.

You'll get a mime message with a payload containing mime parts, e.g. plain text, HTML, quoted printable, attachments, etc.

这篇关于有没有更好的方法通过google-api从gmail获取完整消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆