Gmail Agent Gateway is a secure local API gateway that lets AI agents interact with Gmail through fine-grained, sanitized tools — not direct mailbox access. It handles OAuth 2.0, rate limiting, and operational metrics so you can focus on building the integration scripts your agent actually needs.
- Why This Project?
- Quick Start
- Security Model
- Usage Examples
- Configuration
- API Endpoints
- Example Integration Scripts
- Architecture
- Contributing
- Changelog
- License
- Author
- Related Projects
Integrating AI agents with email poses significant security and engineering challenges:
- Excessive Privilege: Giving an agent raw API credentials or direct access to a full mailbox endpoint creates a high risk of accidental data deletion or unauthorized email transmission.
- Context Bloat & Fragility: Agents should not be parsing nested MIME structures, stripping complex HTML, or handling OAuth handshakes inside their prompt loops.
- Auditability: It is difficult to track, log, and rate-limit email reads, writes, and deletions when they are performed directly by autonomous agent code.
This gateway separates these concerns by exposing secure local REST endpoints that developers consume to build focused, task-specific agent tools.
pip install -e .cp .env.example .env
# Edit .env and configure at least API_KEY, OAUTH_REDIRECT_URI, and OAUTH_CLIENT_SECRETS_FILEmailserver-runOpen https://127.0.0.1:5000/ or https://127.0.0.1:5000/oauth2callback in your browser to authorize Gmail access.
curl -k -H "X-API-Key: <your-api-key>" \
"https://127.0.0.1:5000/api/messages?label_ids=INBOX&max_results=1"Note
Detailed installation, Google Cloud Console OAuth credential creation, and remote VPS/Cloud deployment instructions are available in the Setup and Deployment Guide.
- API Key Authentication: Required on all
/api/*endpoints via theX-API-Keyheader. - Administrative Isolation: Permanent deletions require a separate
X-Admin-Keyheader. - Gmail OAuth 2.0: Mailbox access uses Google OAuth 2.0. Credentials remain local and are never shared.
- Rate Limiting: Built-in in-memory rate limiting enforces mutation control.
- Safe-by-Default Deletions: Standard delete operations move messages to the trash rather than deleting them permanently.
For a full breakdown of the threat model, design mitigations, and production security recommendations, see docs/SECURITY.md and the root SECURITY.md.
curl -k -H "X-API-Key: <your-api-key>" \
"https://127.0.0.1:5000/api/messages?label_ids=INBOX&max_results=2"Response:
{
"success": true,
"messages": [
{
"id": "18f4abc123",
"threadId": "18f4abc123",
"snippet": "Build finished successfully...",
"subject": "CI result",
"from": "ci@example.com"
}
],
"nextPageToken": "1234567890"
}curl -k -X POST "https://127.0.0.1:5000/api/send" \
-H "X-API-Key: <your-api-key>" \
-H "Content-Type: application/json" \
-d '{"to":"recipient@example.com","subject":"Hello","body":"Test"}'Response:
{
"success": true,
"message": {
"id": "18f4abc123",
"threadId": "18f4abc123",
"labelIds": ["SENT"]
}
}Server settings (e.g. ports, API keys, rate limits, and CORS origins) are loaded from environment variables or a .env file.
See the Configuration Reference for the complete list of settings, defaults, and descriptions.
The gateway provides REST endpoints for listing, reading, sending, and labeling emails, alongside operational metrics and token revocation.
See docs/API.md for the detailed API reference, request/response schemas, and example queries.
The repository includes ready-to-use example scripts in the examples/ directory:
- fetch_and_sanitize_unread.py: Retrieves unread emails, strips HTML/scripts, collapses whitespace, redacts secrets/PII, and outputs clean Markdown optimal for LLM prompts.
- attach_labels.py: Applies labels to emails after validating that the requested labels actually exist in the user's mailbox.
flowchart TD
Agent["AI Agent (LLM)"] -->|Runs custom tool| Script["Custom Tools & Scripts\n(e.g., fetch_and_sanitize_unread.py)"]
Script -->|Authenticated via X-API-Key| Flask["Flask API Gateway"]
Browser["Local browser"] --> OAuthRoute["/oauth2callback"]
OAuthRoute --> GoogleOAuth["Google OAuth 2.0"]
GoogleOAuth --> OAuthRoute
Flask --> Auth["API Key & OAuth validation"]
Auth --> GmailService["GmailService"]
GmailService --> GmailAPI["Gmail API"]
Auth --> Metrics["SQLite metrics"]
OAuthRoute --> TokenFile["token_cache.json"]
The Flask layer owns routing, rate limiting, and caller authentication. Custom scripts consume these endpoints to build the actual tools exposed to the agent.
See docs/ARCHITECTURE.md for detailed sequence diagrams, request flows, and component responsibilities.
Contributions are welcome! Please read CONTRIBUTING.md for development setup instructions, code style expectations, and the tag-based release process.
See CHANGELOG.md for release notes and changes between versions.
This project is licensed under the MIT License. See LICENSE for details.
Built by Coderkrp. Found a bug? Open an issue. Have a question? Reach out on GitHub.
- google-api-python-client — Official Google API client library for Python.
- langchain-gmail — Official LangChain Gmail tool integration.