DEV Community

Cover image for Connecting to Gmail API with Python
Adam.S
Adam.S

Posted on • Updated on • Originally published at bas-man.dev

Connecting to Gmail API with Python

This will be a series of articles on implementing a notification system using Gmail and Line Bot

The goal here is to be able to query gmail for a select set of emails. Process them and then send a notification. This could be altered to work with a Bot of some other service.

So let's get started. I am going to take a short cut here because I believe that if there is already a good guide; then you shouldn't rehash what has been done before. Unless you are adding to it. So I would suggest following one of the guides below and then move on to step two when you are ready.

Getting started with Python and Gmail API. Head over to
Python Quick Start or my prefered option A Beginner’s Guide to the Gmail API and Its Documentation which I found to be well presented and informative.

It boils down to, enabling the API, installing the required modules, and copying the provided code. Don't forget to download the credentials file you will be given by Google.

Note: I am going to be using python 3

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Enter fullscreen mode Exit fullscreen mode

Add the folowing code to a file, lets just call it gmail.py

Note: I have removed the following

from __future__ import print_function
Enter fullscreen mode Exit fullscreen mode

Please keep this if you are using Python 2

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # 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'])

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

A note on the sign in process. This may not work if you are using safari, so use Brave or some other browser if needed. You can copy and paste the link generated in your terminal for this.

When you are done. You can move on to the next article in the series.

Top comments (2)

Collapse
 
basman profile image
Adam.S

@shahidul you might like this series more.

Collapse
 
shahidul profile image
Shahidul Islam

Thanks for the info.