【问题标题】:base64 decoding using Python with attachment downloaded with REST-based Gmail API使用 Python 进行 base64 解码,并使用基于 REST 的 Gmail API 下载附件
【发布时间】:2014-08-22 13:47:30
【问题描述】:

我尝试使用新的 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="屏幕截图 2014-03-11 在 11.52.53 PM.png"'], u'Content-Disposition': [u'attachment; filename="2014-03-11 下午 11.52.53 截屏"'], 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 解码吗?

【问题讨论】:

    标签: python gmail gmail-api


    【解决方案1】:

    嗯。 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 示例。非常感谢!
    • 做到了!我试图得到身体,但base64.urlsafe_b64decode 失败了,因为我没有将数据编码为 utf-8。使用base64.b64decode 按原样处理数据(无编码),但给出了奇怪的字符串。我不太明白,因为显然data == data.encode('utf-8') 是真的,但现在它是有道理的:)
    【解决方案2】:

    您需要使用 urlsafe base64 解码。所以 base64.urlsafe_b64decode() 应该这样做。

    【讨论】:

      【解决方案3】:

      我还想指出,您可能想要编写二进制文件。如:

      f = open(path, 'w')
      

      应该是:

      f = open(path, 'wb')
      

      【讨论】:

        猜你喜欢
        • 2022-11-11
        • 2014-11-08
        • 2016-11-21
        • 2018-11-03
        • 2017-04-07
        • 2016-03-28
        • 1970-01-01
        • 2014-09-04
        • 2018-12-15
        相关资源
        最近更新 更多