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.


Part 1

This part is relatively simple, all you need to do is follow this tutorial here
I will outline most important points


  • 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# If modifying these scopes, delete the file token.pickle.
SCOPES = ['']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:
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 to list labels
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', []) if not labels:
print('No labels found.')
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()
if __name__ == '__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.


Leave a Reply

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