Gmail

Read, search, send, and organize Gmail messages with GmailTools using OAuth or a service account.

Gmail enables an Agent to interact with Gmail, allowing it to read, search, send, manage emails, and organize them with labels. Supports both OAuth and service account authentication.

Prerequisites

Install dependencies

uv pip install agno google-api-python-client google-auth-httplib2 google-auth-oauthlib openai

Set up Google OAuth

Follow the Gmail Python quickstart:

  1. Create or select a Google Cloud project and enable the Gmail API.
  2. Configure Google Auth Platform > Branding, including the app name and support contact.
  3. Under Audience, choose the appropriate Internal or External audience. For an external app in Testing, add the Google accounts that will authorize it as test users.
  4. Configure the required Gmail scopes under Data Access. Use gmail.readonly for a tool selection that only reads mail; writing and composing require the corresponding Gmail scopes.
  5. Under Clients, create a Desktop app OAuth client and download its JSON credentials.
  6. Pass its path as credentials_path. The initial interactive sign-in stores access and refresh tokens in token.json in the current directory, or at the writable token_path you supply.

For client credentials from environment variables, set GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and GOOGLE_PROJECT_ID. Publishing an external app with sensitive or restricted scopes may require Google's verification process.

Shared authentication and headless servers

Google toolkits accept one shared AuthConfig, which aggregates their scopes before authentication. For example:

from agno.tools.google.auth import AuthConfig
from agno.tools.google.gmail import GmailTools

auth = AuthConfig(interactive=False, http_timeout=60)
gmail = GmailTools(auth=auth)

This headless configuration requires existing usable credentials or a delegated service account. Gmail tool calls return an authentication error if a browser sign-in would be needed; for the initial local OAuth flow, set interactive=True and provide your client credentials.

AuthConfig(db=...) can store tokens in a supported Agno database. Encryption is enabled by default and requires token_encryption_key or GOOGLE_TOKEN_ENCRYPTION_KEY. The stored Google token uses a shared provider identity (google, with no user ID); an agent's user_id does not choose a separate mailbox. Configure separate credential boundaries in applications that serve different Google accounts.

When using auth=, put service_account_path and delegated_user on AuthConfig. Passing them alongside auth= on GmailTools raises an error. See the AuthConfig source for its full configuration.

Service Account Authentication (Alternative)

For server/bot deployments without browser access:

  1. Create a service account at IAM & Admin > Service Accounts in Google Cloud Console
  2. Download the JSON key file
  3. Configure domain-wide delegation in Google Workspace Admin Console (required for Gmail)
  4. Set environment variables:
export GOOGLE_SERVICE_ACCOUNT_FILE=/path/to/service-account-key.json
export GOOGLE_DELEGATED_USER=user@yourdomain.com  # Required for Gmail

Example

from agno.agent import Agent
from agno.tools.google.gmail import GmailTools

agent = Agent(tools=[GmailTools()])
agent.print_response("Show me my latest 5 unread emails", markdown=True)

Quick Start Examples

# OAuth authentication (browser-based)
from agno.agent import Agent
from agno.tools.google.gmail import GmailTools

agent = Agent(
    tools=[GmailTools(
        credentials_path="path/to/credentials.json"
    )],
    instructions=["You help users manage their Gmail inbox."],
)

# Service account authentication (no browser needed)
agent = Agent(
    tools=[GmailTools(
        service_account_path="path/to/service-account.json",
        delegated_user="user@domain.com"  # Required for Gmail
    )],
)

Most list/search methods cap each requested page at max_results (default 20). Pass a returned nextPageToken as page_token to retrieve another page. This is not a cap on full-thread responses or label-operation batches.

Toolkit Params

ParameterTypeDefaultDescription
authOptional[AuthConfig]NoneShared Google authentication, scope aggregation, and optional database token storage; accepted through the shared base class.
credsCredentialsNonePre-fetched credentials (OAuth or service account) to skip auth flow
credentials_pathstrNonePath to OAuth credentials JSON file
token_pathstrNonePath to token file for storing access/refresh tokens
service_account_pathstrNonePath to service account JSON key. When set, OAuth is skipped
delegated_userstrNoneEmail to impersonate (required for Gmail with service account)
scopesList[str]NoneCustom OAuth scopes
oauth_portint0Port for the OAuth local server. 0 auto-selects a port
login_hintstrNoneEmail to pre-select in OAuth consent screen
include_htmlboolFalseKeep HTML when no plain-text body is available in get_message, get_thread, or get_draft. Legacy list/search helpers do not use this option.
max_body_lengthintNoneBody text limit for get_message, get_thread, and get_draft; legacy list/search helpers bypass it.
attachment_dirstrNoneDirectory to save downloaded attachments
max_resultsint20Default per-page cap for list/search methods; does not bound all tool output.
max_batch_sizeint10Max items per Gmail API batch request (max 100)
get_latest_emailsboolTrueEnable get_latest_emails tool
get_emails_from_userboolTrueEnable get_emails_from_user tool
get_unread_emailsboolTrueEnable get_unread_emails tool
get_starred_emailsboolTrueEnable get_starred_emails tool
get_emails_by_contextboolTrueEnable get_emails_by_context tool
get_emails_by_dateboolTrueEnable get_emails_by_date tool
get_emails_by_threadboolTrueEnable get_emails_by_thread tool
search_emailsboolTrueEnable search_emails tool
mark_email_as_readboolTrueEnable mark_email_as_read tool
mark_email_as_unreadboolTrueEnable mark_email_as_unread tool
star_emailboolTrueEnable star_email tool
unstar_emailboolTrueEnable unstar_email tool
archive_emailboolFalseEnable archive_email tool
create_draft_emailboolTrueEnable create_draft_email tool
send_emailboolTrueEnable send_email tool
send_email_replyboolTrueEnable send_email_reply tool
list_custom_labelsboolTrueEnable list_custom_labels tool
apply_labelboolTrueEnable apply_label tool
remove_labelboolTrueEnable remove_label tool
delete_custom_labelboolTrueEnable delete_custom_label tool
get_messageboolTrueEnable get_message tool
get_threadboolTrueEnable get_thread tool
search_threadsboolTrueEnable search_threads tool
modify_thread_labelsboolFalseEnable modify_thread_labels tool
trash_threadboolFalseEnable trash_thread tool
get_draftboolTrueEnable get_draft tool
list_draftsboolTrueEnable list_drafts tool
send_draftboolFalseEnable send_draft tool
update_draftboolTrueEnable update_draft tool
list_labelsboolFalseEnable list_labels tool
modify_message_labelsboolFalseEnable modify_message_labels tool
trash_messageboolFalseEnable trash_message tool
download_attachmentboolFalseEnable download_attachment tool

Toolkit Functions

Reading Emails

FunctionDescription
get_latest_emailsGet the latest emails across the mailbox (no implicit INBOX filter). Parameters: count (int), page_token (Optional[str])
get_emails_from_userGet emails from a specific sender. Parameters: user (str), count (int), page_token (Optional[str])
get_unread_emailsGet unread emails. Parameters: count (int), page_token (Optional[str])
get_starred_emailsGet starred emails. Parameters: count (int), page_token (Optional[str])
get_emails_by_contextGet emails matching a context. Parameters: context (str), count (int), page_token (Optional[str])
get_emails_by_dateGet emails within a date range. Parameters: start_date (str), range_in_days (int), num_emails (int), page_token (Optional[str])
get_emails_by_threadGet all emails from a thread. Parameters: thread_id (str)
search_emailsSearch using Gmail query syntax, forwarded unchanged. Parameters: query (str), count (int), page_token (Optional[str])
get_messageGet a specific message by ID. Parameters: message_id (str), download_attachments (bool)
get_threadGet all messages in a thread. Parameters: thread_id (str)
search_threadsSearch email threads. Parameters: query (str), count (int), page_token (Optional[str])

Managing Emails

FunctionDescription
mark_email_as_readMark email as read. Parameters: message_id (str)
mark_email_as_unreadMark email as unread. Parameters: message_id (str)
star_emailStar an email. Parameters: message_id (str)
unstar_emailUnstar an email. Parameters: message_id (str)
archive_emailArchive an email. Parameters: message_id (str)
trash_messageMove message to trash, or restore with undo. Parameters: message_id (str), undo (bool)
trash_threadMove thread to trash. Parameters: thread_id (str)
download_attachmentDownload email attachment. Parameters: message_id (str), attachment_id (str), filename (str)

Composing & Sending

FunctionDescription
create_draft_emailCreate draft with attachments. Parameters: to (str), subject (str), body (str), cc (str), bcc (str), attachments (str or List[str]), thread_id (str), message_id (str)
send_emailSend email with attachments. Parameters: to (str), subject (str), body (str), cc (str), bcc (str), attachments (str or List[str]), thread_id (str), message_id (str)
send_email_replyReply to email thread. Parameters: thread_id (str), message_id (str), to (str), subject (str), body (str), cc (str), attachments (str or List[str])
get_draftGet draft by ID. Parameters: draft_id (str)
list_draftsList one page of draft IDs. Parameters: count (int), page_token (Optional[str])
send_draftSend a draft. Parameters: draft_id (str)
update_draftUpdate draft content. Parameters: draft_id (str), to (str), subject (str), body (str), cc (str), bcc (str), attachments (str or List[str]), thread_id (str), message_id (str)

Label Management

FunctionDescription
list_labelsList all labels in the account. No parameters
list_custom_labelsList user-created labels. No parameters
apply_labelApply label to emails. Parameters: context (str), label_name (str), count (int)
remove_labelRemove label from emails. Parameters: context (str), label_name (str), count (int)
delete_custom_labelDelete a custom label. Parameters: label_name (str), confirm (bool)
modify_message_labelsModify message labels. Parameters: message_id (str), add_labels (str, comma-separated), remove_labels (str, comma-separated)
modify_thread_labelsModify thread labels. Parameters: thread_id (str), add_labels (str, comma-separated), remove_labels (str, comma-separated)

You can use include_tools or exclude_tools to modify the list of tools the agent has access to. Learn more about selecting tools.

Cookbook Examples

The agno cookbook includes several Gmail examples demonstrating different use cases:

ExampleDescription
basic.pyCore examples: read-only agent, safe agent, label manager, full agent, thread reply
daily_digest.pySummarize recent emails into a structured daily digest grouped by priority
draft_reply.pyRead a conversation thread and draft a contextual reply for human review
inbox_triage.pyPersonal inbox triage agent with Learning Machine for persistent preferences
followup_tracker.pyFind unanswered sent emails, draft follow-ups
action_items.pyExtract structured action items from email threads

For send_email_reply, supply the recipient (to), subject, and body along with the original message/thread identifiers. The current validator still requires recipient and subject; a call with only message_id and body fails.

Tips for Using Gmail Tools

  1. Authentication:

    • Use OAuth for user-facing applications (requires browser)
    • Use service accounts for server/bot deployments (requires domain-wide delegation)
  2. Search Queries: Agent instructions guide the model to translate a request into Gmail syntax, such as is:unread newer_than:7d. The Python tool forwards that query unchanged.

  3. Attachments: When sending emails with attachments, provide file paths as strings or a list of strings.

  4. Thread Management: Use thread operations (get_thread, trash_thread, etc.) to manage entire conversations.

  5. Label Operations: Gmail's label system is hierarchical - use forward slashes for nested labels (e.g., "Work/Projects").

  6. Rate Limits: Be mindful of Gmail API quotas when performing bulk operations.

Developer Resources