Gmail API无法获取电子邮件数据 [英] Gmail API cannot get email data
本文介绍了Gmail API无法获取电子邮件数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用gmail API打印电子邮件:
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))
它正确打印了第一封电子邮件,但是在第二封for循环中,我得到了'data'
的 KeyError
.如果我尝试通过执行 print(msg ['snippet'])
打印每封电子邮件的代码段,则效果很好.
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.
推荐答案
msg ['payload'] ['body'] ['data']
会返回电子邮件附件,但不是每封邮件有附件.
msg['payload']['body']['data']
returns you the email attachment, but not every message has an attachment.
- 如果要在附件存在的地方进行检索,请执行条件语句以验证
msg ['payload'] ['body'] ['size']
在继续进行解码和打印之前不等于0
- 如果要检索邮件正文内容而不是附件,则可以按照文档中的说明进行操作
- 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
这篇关于Gmail API无法获取电子邮件数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文