Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download attachment from Gmail in python: no "data" key

I am using the official Google tutorials to connect to a gmail address and download attachments from an e-mail using the Gmail API.

The sample code given goes like this:

try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

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

except errors.HttpError, error:
        print 'An error occurred: %s' % error

I am systematically getting a KeyError: 'data'.

When I print the "part" object, I get this. I have checked that all the e-mail contain attachments and I see that the "body" key has "attachmentId" and "size" fields, but no "data" field.

{'partId': '1',
 'mimeType': 'application/x-zip-compressed',
 'filename': 'Statement.zip',
 'headers': [{'name': 'Content-Type', 'value': 'application/x-zip-compressed; name="Statement.zip"'},
             {'name': 'Content-Description', 'value': 'Statement.zip'},
             {'name': 'Content-Disposition', 'value': 'attachment; filename="Statement.zip"; size=317; creation-date="Fri, 05 Oct 2018 11:00:24 GMT"; modification-date="Fri, 05 Oct 2018 11:00:24 GMT"'},
             {'name': 'Content-Transfer-Encoding', 'value': 'base64'}],
 'body': {'attachmentId': 'ANGjdJ8Jsk95qxfAezayex3yDktM9hnMSwsy_LD4aqu3h2lhum36MT7pG9aqyWpX7VmNoxZISLAFfKyBy0gGgL5WyL5f7zrH4bRd_MBsHtGxXBfN6XBCg_qHkRu0ZVRaOtuYTCc8_aN4NMsaApGI19KJlfgVXV3w67gEspZ61OKZZwbt386wbA-_6GrAcQCGIgk4dFGxc_Zp5EjqIbsA557KOjEFoO0A9urMXIQvQXF0GRdhfHb287ZfhjKYGVpukhVxT6wDNjL47Ifc7VmG_kcgeUxpfKEGO6tmVw2PzuG4RlAdX5S7yjgGlEHGVmPgnTl-rjT7asZnia68cBg_5ATSJ9FS64OKcr79s8MQD-DL0omXLJjfw5-qIOUKM4x56btte572j5SO7afAYrsv',
          'size': 317}}

So I am not getting the same content as the official Google documentation. Am i missing something? How can I download the attachment?

like image 420
Alexis Eggermont Avatar asked Oct 11 '18 12:10

Alexis Eggermont


People also ask

How to use Gmail to send emails with Python script?

To use a Gmail account to send emails with a third party app, e.g. Python script, in this case, we need to set up an app password. For security reasons, the normal Gmail password is restricted to web login only.

How to backup Gmail emails with attachments?

It downloads emails with attachments. 1. Gmail Backup Software can be download and installed on your computer. 2. Enter your Gmail account’s username and password, then click the Login button to verify your account. 3. Choose the Category of items from your Gmail account that you want to backup.

How to fix Gmail attachments not downloading issue?

Many Gmail users are there who can’t download attachments from Gmail in different browsers, some of them support Google and some don’t. If you cant download email attachments from Gmail in chrome, firefox, or any other browser, then a quick way is to fix the issue is by taking help from third-party DRS Gmail Email Backup software.

How to download attachments from Confidential mode in Gmail?

If the sender sends the message with Confidential Mode ON. Then, you will not be able to print, download, save the attachments of an email. There is no method available to solve your problem if the Confidential Mode is On in Gmail while sending or receiving the emails. So ask the sender to remove this mode to download the Gmail attachment.


1 Answers

Found a different syntax that works:

  try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

    for part in message['payload']['parts']:
      if part['filename']:        
        attachment = service.users().messages().attachments().get(userId='me', messageId=message['id'], id=part['body']['attachmentId']).execute()
        file_data = base64.urlsafe_b64decode(attachment['data'].encode('UTF-8'))

        path = ''.join([store_dir, part['filename']])

        f = open(path, 'wb')
        f.write(file_data)
        f.close()

  except errors.HttpError as error:
    print(f'An error occurred: {error}')
like image 122
Alexis Eggermont Avatar answered Sep 18 '22 16:09

Alexis Eggermont