6
votes

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?

2

2 Answers

8
votes

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}')
1
votes

On your seventh line, you use part['body']['data']. However, in the part you print, the 'body' doesn’t have a 'data' key. It only has 'attachmentId' and 'size'.