Connecting to Gmail API with Python
Tags: google, python, api, line
Published: 2021-02-01 06:19:17

This will be a series of articles on implementing a notification system using Gmail and [Line Bot](https://notify-bot.line.me/doc/en/)  
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](https://developers.google.com/gmail/api/quickstart/python) or my prefered option [A Beginner’s Guide to the Gmail API and Its Documentation](https://medium.com/better-programming/a-beginners-guide-to-the-google-gmail-api-and-its-documentation-c73495deff08) 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
```

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

*Note: I have removed the following*
```
from __future__ import print_function
```
Please keep this if you are using Python 2

```python
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()
```
 
*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.