用python从Gmail下载附件:没有“data”键

2024-04-25 17:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Google官方教程连接到gmail地址,并使用Gmail API从电子邮件下载附件。在

给定的示例代码如下:

try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

    for part in message['payload']['parts']:
      if part['filename']:
        file_data = base64.urlsafe_b64decode(part['body']['data']
                                             .encode('UTF-8'))

        path = ''.join([store_dir, part['filename']])

        f = open(path, 'w')
        f.write(file_data)
        f.close()   

except errors.HttpError, error:
        print 'An error occurred: %s' % error

我系统地得到了一个KeyError:'数据'。在

当我打印“part”对象时,我得到这个。我已经检查了所有的电子邮件都包含附件,我看到“body”键有“attachmentId”和“size”字段,但没有“data”字段。在

^{pr2}$

所以我得到的内容和谷歌官方文档不一样。我错过什么了吗?如何下载附件?在


Tags: pathidmessagedata附件官方电子邮件google
2条回答

在第七行中,使用part['body']['data']。但是,在您打印的部分中,'body'没有'data'键。它只有'attachmentId'和{}。在

找到了另一种有效的语法:

  try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

    for part in message['payload']['parts']:
      if part['filename']:        
        attachment = service.users().messages().attachments().get(userId='me', messageId=message['id'], id=part['body']['attachmentId']).execute()
        file_data = base64.urlsafe_b64decode(attachment['data'].encode('UTF-8'))

        path = ''.join([store_dir, part['filename']])

        f = open(path, 'wb')
        f.write(file_data)
        f.close()

  except errors.HttpError as error:
    print(f'An error occurred: {error}')

相关问题 更多 >