2014-07-01 32 views
2

我試圖使用新的Gmail api從特定的電子郵件部分下載圖像附件。 (https://developers.google.com/gmail/api/v1/reference/users/messages/attachments#resource)。使用Python進行base64解碼,附件使用基於REST的Gmail API下載附件

的消息部分是:

{u'mimeType ':u'image/PNG',u'headers ':{u'Content傳送編碼':[u'base64 ']中,u'內容類型':[u'image/png; name =「Screen Shot 2014-03-11 at 11.52.53 PM.png」'],u'Content-Disposition':[u'attachment;文件名=「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'}

GET Users.messages.attachments的響應爲:

{ 「數據」: 「」, 「大小」: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

hmm。 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() 
+0

就是這樣。我沒有注意到有一個python例子可用。非常感謝! – wyang

+0

這樣做!我試圖獲取body,但是'base64.urlsafe_b64decode'失敗了,因爲我沒有將數據編碼爲utf-8。使用'base64.b64decode'原樣處理數據(無編碼),但給出了奇怪的字符串。我不明白它,因爲顯然'data == data.encode('utf-8')'是真的,但它現在有意義:) – guival

2

您需要使用urlsafe base64解碼。所以base64.urlsafe_b64decode()應該這樣做。

2

我還想指出,你可能會想寫二進制文件。如:

f = open(path, 'w') 

應該是:

f = open(path, 'wb')