python - 使用 Python 进行 base64 解码,附件通过基于 REST 的 Gmail API 下载

标签 python gmail gmail-api

我尝试使用新的 Gmail api 从特定的电子邮件消息部分下载图像附件。 (https://developers.google.com/gmail/api/v1/reference/users/messages/attachments#resource)。

消息部分是:

{u'mimeType': u'image/png', u'headers': {u'Content-Transfer-Encoding': [u'base64'], u'Content-Type': [u'image/PNG; name="Screen Shot 2014-03-11 at 11.52.53 PM.png"'], u'Content-Disposition': [u'attachment; filename="Screen Shot 2014-03-11 at 11.52.53 PM.png"'], u'X-Attachment-Id': [u'f_hso95l860']}, u'body': {u'attachmentId': u '', u'size': 266378}, u'partId': u'1', u'filename': u'Screen Shot 2014-03-11 at 11.52.53 PM.png'}

Users.messages.attachments 的 GET 响应是:

{ “数据”: ””, “尺寸”:194659

当我用Python解码数据时如下:

decoded_data1 = base64.b64decode(resp["data"])
decoded_data2 = email.utils._bdecode(resp["data"]) # email, the standard module
with open("image1.png", "w") as f:
    f.write(decoded_data1)
with open("image2.png", "w") as f:
    f.write(decoded_data2)

文件 image1.png 和 image2.png 的大小都是 188511,它们是无效的 png 文件,因为我无法在图像查看器中打开它们。我没有为 MIME 正文使用正确的 base64 解码吗?

最佳答案

嗯。 Gmail API 看起来与标准的 Python email 模块有点不同,但我确实找到了一个如何下载和存储附件的示例:

https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get#examples

例子

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()

关于python - 使用 Python 进行 base64 解码,附件通过基于 REST 的 Gmail API 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24519773/

相关文章:

python - 使用 python 和 postfix 发送符合 VERP 标准的电子邮件

email - 糟糕的 Google Postmaster 域声誉

java - Gmail API 导入 AuthorizationCodeInstalledApp 和 LocalServerReceiver 类

php - 客户端未经授权使用此方法检索访问 token 服务帐户错误

python - 使用递归计算纳 PIL 常数 (e)

python - 语法错误 : invalid syntax Python 2. 7

php - 电子邮件的动态图像,例如倒计时时钟(根据 gmail 图像缓存)

php - Gmail 是否不允许发件人设置返回路径值以接收退回邮件?

api - Gmail API - 元数据范围不支持 'q' 参数

python - Keras 看不到训练和验证文件夹中的所有图像