Integrating python gmail API using service account to fetch e.g. oauth

15.10.2023 | by Ralph Van Der Horst

Integrating python Gmail 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-auth-oauthlib 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