Is there any nicer way to get the full message from gmail with google-api

谁说胖子不能爱 提交于 2020-01-23 21:38:33

问题


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'])

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

回答1:


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

According to the official 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)

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



来源:https://stackoverflow.com/questions/34922074/is-there-any-nicer-way-to-get-the-full-message-from-gmail-with-google-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!