2

新しい 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="2014 年 3 月 11 日午後 11 時 52 分 53 秒のスクリーンショット.png"']、u'X-Attachment-Id': [u'f_hso95l860']}、u'body': {u'attachmentId': u '', u'size': 266378}, u'partId': u'1', u'filename': u'スクリーンショット 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 デコードを使用していませんか?

4

3 に答える 3

6

うーん。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()
于 2014-07-01T22:16:24.583 に答える
2

また、バイナリを書きたくなる可能性が高いことにも注意してください。そのような:

f = open(path, 'w')

次のようにする必要があります。

f = open(path, 'wb')
于 2014-07-23T00:22:45.530 に答える
2

urlsafe base64 デコードを使用する必要があります。したがって、 base64.urlsafe_b64decode() で実行する必要があります。

于 2014-07-02T00:09:42.680 に答える