Download Attachments from gmail using Gmail API

Rahul Kulhari picture Rahul Kulhari · Sep 14, 2014 · Viewed 20.5k times · Source

I am using Gmail API to access my gmail data and google python api client.

According to documentation to get the message attachment they gave one sample for python

https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get

but the same code i tried then i am getting error:

AttributeError: 'Resource' object has no attribute 'user'

line where i am getting error:

message = service.user().messages().get(userId=user_id, id=msg_id).execute()

So i tried users() by replacing user()

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

but i am not getting part['body']['data'] in for part in message['payload']['parts']

Answer

Ilya V. Schurov picture Ilya V. Schurov · Dec 6, 2014

Expanding @Eric answer, I wrote the following corrected version of GetAttachments function from the docs:

# based on Python example from 
# https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get
# which is licensed under Apache 2.0 License

import base64
from apiclient import errors

def GetAttachments(service, user_id, msg_id):
    """Get and store attachment from Message with given id.

    :param service: Authorized Gmail API service instance.
    :param user_id: User's email address. The special value "me" can be used to indicate the authenticated user.
    :param msg_id: ID of Message containing attachment.
    """
    try:
        message = service.users().messages().get(userId=user_id, id=msg_id).execute()

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

                with open(path, 'w') as f:
                    f.write(file_data)

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