How to access Gmail using Python

In a previous post we saw how you could access Gmail in NodeJS. In this post we will see how we can access Gmail using Python.

Turning on the Gmail api

You first need to enable Gmail api and get the required OAuth credentials from your Google account. The steps which are shown below.

1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.

2. On the Add credentials to your project page, click the Cancel button.

3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.

4. Select the Credentials tab, click the Create credentials button and select OAuth client ID.

5. Select the application type Other, enter the name “Gmail API Quickstart”, and click the Create button.

6. Click OK to dismiss the resulting dialog.

7. Click the Download JSON button to the right of the client ID.

8. Move this file to your working directory and rename it client_secret.json.

Install the Gmail api Python library.

pip install --upgrade google-api-python-client

Once the above process has been done run the following Python file and you will get the list of labels for your Gmail account.

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
 
# Setup the Gmail API
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
 
# Call the Gmail API
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
    print('No labels found.')
else:
    print('Labels:')
    for label in labels:
        print(label['name'])

Now to get an actual message from Gmail we will use the following code. The initial authorization code is the same, just the api calls change.

# Call the Gmail API, only get 1 of the the recent message ids
# First get the message id for the message
results = service.users().messages().list(userId='me', maxResults=1).execute()
 
# get the message id from the results object
message_id = results['messages'][0]['id']
 
# use the message id to get the actual message, including any attachments
message = service.users().messages().get(userId='me', id=message_id).execute()
 
# now the message object contains the entire recent message

Detailed functions list for accessing the Gmail api is given here.

Leave a Reply

Your email address will not be published. Required fields are marked *