Connecting to Gmail via the API
Google API client library, OAuth2 consent, and Gmail scope selection.
Why Use the Gmail API Instead of SMTP?
Traditional email automation uses SMTP/IMAP, but the Gmail API offers much more: read threads, search by query, manage labels, and send with full authentication. It also supports OAuth 2.0, so your agent never stores a password — just a limited-scope access token.
The Gmail API is part of the Google Workspace APIs, accessed via the google-api-python-client library.
# Install required libraries:
# pip install google-api-python-client google-auth google-auth-oauthlib
# The Gmail API lets agents:
# - List and search messages (labels, queries)
# - Read full message content and attachments
# - Send messages via OAuth (no password needed)
# - Manage labels and threads
# - Watch for new messages via push notifications
print('Gmail API is part of Google Workspace APIs')Authentication: Service Account vs User Auth
Two authentication approaches exist for the Gmail API:
- Service Account: best for workspace/organizational use with domain-wide delegation; no user interaction required
- User OAuth (OAuth2 with consent screen): required for personal Gmail accounts; user grants access once, agent uses refresh token
For most agent automation, service accounts are preferred for reliability.
# Service Account approach:
# 1. Go to Google Cloud Console -> APIs & Services -> Credentials
# 2. Create a Service Account
# 3. Download the JSON key file
# 4. In Google Workspace Admin: enable domain-wide delegation
# 5. Grant required scopes to the service account
# User OAuth approach:
# 1. Create OAuth 2.0 Client ID (Desktop or Web App type)
# 2. Download credentials.json
# 3. First run: user sees consent screen and grants access
# 4. Agent stores token.json with refresh token for subsequent runs
print('Choose service account for org automation, OAuth for personal Gmail')All lessons in this course
- Connecting to Gmail via the API
- Reading and Sending Emails Programmatically
- Calendar Event Creation and Querying
- Building a Simple Email Assistant Agent