Gmail API cannot get email data

那年仲夏 提交于 2021-01-29 16:17:12

问题


I am trying to print my email messages using the gmail API:

results = service.users().messages().list(userId='me',labelIds = ['INBOX']).execute()

messages = results.get('messages', [])

if not messages:
    print("No messages found.")
else:
    count = 0 
    for message in messages:
        count += 1

        msg = service.users().messages().get(userId='me', id=message['id']).execute()

        full_msg = base64.urlsafe_b64decode(msg['payload']['body']['data'].encode("ASCII")).decode("utf-8")
        print("Email {}: {}".format(count, full_msg))

It prints the first email properly, but on the second for loop I get a KeyError for 'data'. If I try to print the snippet of each email by doing print(msg['snippet']), it works fine.


回答1:


msg['payload']['body']['data'] returns you the email attachment, but not every message has an attachment.


  • If you want to retrieve the attachment where it exists - implement a conditional statement to verify either msg['payload']['body']['size'] is not equal to 0 before proceeding with decoding and printing
  • If you want retrieve the message body content instead of the attachment, you can do it as specified in the documentation


来源:https://stackoverflow.com/questions/61839869/gmail-api-cannot-get-email-data

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