How can I check a Gmail inbox programmatically for testing?

Hello,

I am building out automated testing that needs to confirm a Gmail inbox is active and check the messages in it.

The user is a single test user whom I have made an Admin on the Service Account I have created for this purpose.

Checking the inbox must be 100% programmatically done so I can’t use a standard OAuth2 flow that requires user interaction. - I am trying to do a server-to-server call using an API key/secret.

The documentation around accessing GMail inboxes is confusing to me.

Any help would be greatly appreciated.

Geoff

Gemini.

from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials

Replace with your service account file path and test user email

SERVICE_ACCOUNT_FILE = ‘path/to/your/key.json’
TEST_USER_EMAIL = ‘testuser@example.com’

def get_gmail_service():
creds = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=[‘https://www.googleapis.com/auth/gmail.readonly’])
creds = creds.with_subject(TEST_USER_EMAIL)
service = build(‘gmail’, ‘v1’, credentials=creds)
return service

def check_inbox(service):

Use the service object to make API calls to check the inbox

For example, to list messages:

results = service.users().messages().list(userId=‘me’).execute()
messages = results.get(‘messages’, )

if not messages:
print(‘No messages found.’)
else:
print(‘Messages:’)
for message in messages:
msg = service.users().messages().get(userId=‘me’, id=message[‘id’]).execute()
print(msg[‘snippet’])

if name == ‘main’:
service = get_gmail_service()
check_inbox(service)

1 Like