使用Python解码通过REST Gmail API下载的附件的base64
我尝试使用新的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'}
获取用户邮件附件的响应是:
{ "data": "", "size": 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文件,我无法在图片查看器中打开它们。难道我没有正确使用base64解码来处理MIME内容吗?
3 个回答
我还想提一下,你可能会想要写成二进制的形式。比如:
f = open(path, 'w')
应该是:
f = open(path, 'wb')
你需要使用一种叫做urlsafe的base64解码方式。所以可以用base64.urlsafe_b64decode()这个方法来实现。
嗯,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()