问题
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 to0
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