Integrating python gmail API using service account

Feb 25, 2024 | by Ralph Van Der Horst

Integrating Python Gmail Api Using Service Account

Integrating PythonGmail Api Using Service Account to Fetch E.g. Oauth

In the past I created a blog post regarding integrating google sheets api with katalon studio via service account.

You can also do this in python:

Set Up Service Account & Download Credentials

  • Go to the Google Cloud Console.
  • Create a new project or select an existing project.
  • Navigate to IAM & Admin > Service Accounts and click on “Create Service Account”.
  • Fill out the necessary information and click “Create”.
  • Grant the service account the necessary permissions (for Gmail API: Gmail API > Gmail API User).
  • Click on “Continue” and then “Done”.
  • Click on the newly created service account to view its details.
  • In the Keys tab, click on “Add Key” and select “JSON”. This will download a JSON key file. Keep this file secure.
  • Share the mailbox with the service account by going to your Gmail settings > Accounts and Import > Grant access to your account.
  • Install Necessary Libraries You’ll need the google-auth and google-api-python-client libraries. You can install them via pip:
pip install --upgrade google-auth google-autho-authlib google-auth-httplib2 google-api-python-client
import google.auth
from google.oauth2 import service_account
from googleapiclient.discovery import build
import base64

# Load the credentials
SERVICE_ACCOUNT_FILE = 'path_to_service_account.json'
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']


credentials = service_account.Credentials.from_service_account_file(
   SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# The email ID for the user you're trying to impersonate.
user_email = 'your_email@gmail.com'
delegated_credentials = credentials.with_subject(user_email)

# Build the Gmail API client
service = build('gmail', 'v1', credentials=delegated_credentials)

# Define your query
query = "from:example@example.com subject:'Important'"

# Filter messages based on the query
results = service.users().messages().list(userId='me', q=query, maxResults=10).execute()
messages = results.get('messages', [])

for message in messages:
   msg = service.users().messages().get(userId='me', id=message['id']).execute()

   # Get the message body
   msg_body = base64.urlsafe_b64decode(msg['payload']['body']['data']).
decode('utf-8').print(msg_body)

Things to update

Replace path_to_service_account.json with the path to your service account JSON file and your_email@gmail.com with the email address you want to read messages from.

Replace the query variable’s value with the desired filtering condition. In the above example, it filters messages from example@example.com with a subject containing the word “Important”. The q parameter supports various query combinations just like the Gmail search box. Some examples include:

If you’re looking to filter messages in Gmail programmatically using the Gmail API and Python, you can make use of the q parameter in the list method of the Gmail API. The q parameter supports the same query format that you use in Gmail’s search box.

by Ralph Van Der Horst

arrow right
back to blog

share this article

Relevant articles

ISTQB Advanced level

ISTQB Advanced level

Setup oauth2 client for Salesforce dev env for API testing using curl postman and Katalon

Setup oauth2 client for Salesforce dev env for API testing using curl postman and Katalon

Setup oauth2 client for Salesforce dev env for API testing using curl postman and Katalon

Setup oauth2 client for Salesforce dev env for API testing using curl postman and Katalon