Online expense tracker — Part 1 — Setting up access to Gmail
Tags: expense, tracker, python
Published: 2020-04-20 11:01:19

Original post appeared [here](https://giosal.ge/blog/index.php/2020/04/18/online-expense-tracker-part-1-setting-up-access-to-gmail/)

I’ve decided to write a python program that parses my emails from Gmail and finds the emails that contain information about my online spending — online shopping as well as monthly subscriptions.
So this is a series of posts describing how to do it. The content will be updated as I add new posts.

#Contents
Part 1 — Setting up access to Gmail

##Part 1
This part is relatively simple, all you need to do is follow this tutorial here (https://developers.google.com/gmail/api/quickstart/python)

I will outline most important points

###Prerequisites
Python 2.6 or greater
The pip package management tool
A Google account with Gmail enabled
I do recommend using Python 3 and pip3 to get the best and latest

###Step 1: Turn on the Gmail API
Click this button to create a new Cloud Platform project and automatically enable the Gmail API
In resulting dialog click DOWNLOAD CLIENT CONFIGURATION and save the file credentials.json to your working directory.

###Step 2: Install the Google Client Library
Run the following command to install the library using pip:
`pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib`
or you can run pip3 instead of pip if you’re using python3

###Step 3: Set up the sample
Create a new file with any name in your working directory and copy in the following code:
```from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
    creds = None
    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)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    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'])
        # Call the Gmail API to fetch INBOX
        results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
        messages = results.get('messages', [])
        for message in messages:
            msg = service.users().messages().get(userId='me', id=message['id']).execute()
            print(msg['snippet'])
if __name__ == '__main__':
    main()```

Be aware that by default messages().list returns only the first page (within UI) of your emails. In my case, Gmail is set to show 100 emails per page, so it returns 100 latest emails. If you want to display more, just add maxResults=number after labelIds.

###Sources
Gmail API Python Quickstart — (https://developers.google.com/gmail/api/quickstart/python)