Google Mail Integration - Project Plan v1.0
Project: CODITECT Google Mail (Gmail) Integration Version: 1.0.0 Status: Planning Last Updated: December 17, 2025
Executive Summary
This project delivers a zero-cost Gmail integration as an optional CODITECT component, enabling programmatic email sending, receiving, inbox monitoring, and AI-powered email analysis for meeting workflows.
Key Objectives
- Zero External Cost - Use only free-tier Gmail API quotas
- Optional Component - Activatable only when needed
- Provider Agnostic - Abstract interface for multi-provider support
- CODITECT Native - Follow framework patterns and conventions
- Meeting Integration - Seamless with Google Meet and Zoom
Success Criteria
- All free-tier APIs integrated and tested
- 80%+ unit test coverage
- Documentation complete (SDD, TDD, ADRs)
- Component activation workflow functional
- Push notifications working via Pub/Sub
- Integration with meeting providers working
Phase 0: GCP Project Setup (Prerequisites)
0.1 Google Cloud Project Configuration
Duration: 1 day
-
Create or select GCP project
- Project ID:
coditect-integrations(or existing) - Enable billing (required for API access, but free tier used)
- Console: https://console.cloud.google.com/
- Project ID:
-
Enable required APIs via GCP Console or CLI
# Enable Gmail API
gcloud services enable gmail.googleapis.com
# Enable Cloud Pub/Sub (for push notifications)
gcloud services enable pubsub.googleapis.com
# Enable IAM API (for service accounts)
gcloud services enable iam.googleapis.com
# Verify enabled APIs
gcloud services list --enabled
0.2 API Endpoints Reference
| API | Endpoint Base | Documentation |
|---|---|---|
| Gmail API v1 | https://gmail.googleapis.com/gmail/v1 | https://developers.google.com/gmail/api |
| Cloud Pub/Sub v1 | https://pubsub.googleapis.com/v1 | https://cloud.google.com/pubsub/docs |
| OAuth 2.0 | https://oauth2.googleapis.com | https://developers.google.com/identity |
| Token Info | https://oauth2.googleapis.com/tokeninfo | - |
| Token Revoke | https://oauth2.googleapis.com/revoke | - |
0.3 OAuth 2.0 Credentials Setup
Duration: 2 hours
-
Create OAuth 2.0 Client ID
- Go to: APIs & Services → Credentials
- Click "Create Credentials" → "OAuth client ID"
- Application type: "Web application"
- Authorized redirect URIs:
http://localhost:8080/oauth/callback(development)https://your-domain.com/oauth/callback(production)
- Download client credentials JSON
-
Configure OAuth Consent Screen
- Go to: APIs & Services → OAuth consent screen
- User type: External (or Internal for Workspace)
- App name: "CODITECT Gmail Integration"
- User support email: support@coditect.ai
- Scopes: Add Gmail scopes (see below)
- Test users: Add test Gmail accounts
-
Required OAuth Scopes
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.labels
0.4 Service Account Setup (Optional - Enterprise)
Duration: 1 hour
-
Create Service Account
# Create service account
gcloud iam service-accounts create gmail-integration \
--display-name="CODITECT Gmail Integration"
# Download key file
gcloud iam service-accounts keys create gmail-sa-key.json \
--iam-account=gmail-integration@PROJECT_ID.iam.gserviceaccount.com -
Enable Domain-Wide Delegation (Workspace only)
- Go to: IAM & Admin → Service Accounts
- Click on service account → Edit → Show Advanced Settings
- Enable "Domain-wide Delegation"
- Copy Client ID for Admin Console
-
Configure in Google Workspace Admin Console
- Go to: admin.google.com → Security → API Controls → Domain-wide Delegation
- Add new → Client ID from service account
- OAuth Scopes: (same as user OAuth)
0.5 Cloud Pub/Sub Setup
Duration: 1 hour
-
Create Pub/Sub Topic
# Create topic for Gmail push notifications
gcloud pubsub topics create gmail-push-notifications
# Grant Gmail API permission to publish
gcloud pubsub topics add-iam-policy-binding gmail-push-notifications \
--member="serviceAccount:gmail-api-push@system.gserviceaccount.com" \
--role="roles/pubsub.publisher" -
Create Pub/Sub Subscription
# For push delivery (production)
gcloud pubsub subscriptions create gmail-push-sub \
--topic=gmail-push-notifications \
--push-endpoint=https://your-domain.com/webhooks/gmail \
--ack-deadline=60
# For pull delivery (development)
gcloud pubsub subscriptions create gmail-pull-sub \
--topic=gmail-push-notifications \
--ack-deadline=60 -
Verify Pub/Sub Permissions
# List topic IAM policy
gcloud pubsub topics get-iam-policy gmail-push-notifications
0.6 Environment Variables
Duration: 30 minutes
-
Create
.envfile with credentials# OAuth 2.0
GMAIL_CLIENT_ID=your-client-id.apps.googleusercontent.com
GMAIL_CLIENT_SECRET=your-client-secret
GMAIL_REDIRECT_URI=http://localhost:8080/oauth/callback
# Service Account (optional)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/gmail-sa-key.json
GMAIL_DELEGATED_USER=admin@yourdomain.com
# Pub/Sub
GOOGLE_CLOUD_PROJECT=your-project-id
GMAIL_PUBSUB_TOPIC=gmail-push-notifications
GMAIL_PUBSUB_SUBSCRIPTION=gmail-push-sub
# Security
TOKEN_ENCRYPTION_KEY=<32-byte-base64-key> -
Add
.envto.gitignore -
Create
.env.examplewith placeholder values
Phase 1: Foundation
1.1 Project Setup
Duration: 2 days
- Create project structure
-
src/directory with__init__.py -
tests/directory with__init__.py -
config/directory with default.yaml -
docs/directory (already created)
-
- Set up
pyproject.tomlwith dependencies - Configure pytest and coverage
- Set up pre-commit hooks
- Create
.gitignorefor secrets
1.2 Email Provider Interface
Duration: 2 days
- Define
EmailProviderInterfaceabstract base class- Import:
from coditect_integrations.email import EmailProviderInterface -
authenticate()method -
send_email()method -
get_message()method -
list_messages()method -
search()method -
get_thread()method -
watch_inbox()method -
stop_watch()method -
add_label()/remove_label()methods
- Import:
- Create data models
-
EmailMessagedataclass -
EmailThreaddataclass -
Attachmentdataclass -
EmailLabeldataclass
-
- Define exception hierarchy
-
EmailIntegrationErrorbase -
EmailAuthenticationError -
EmailRateLimitError -
EmailNotFoundError -
EmailSendError
-
1.3 OAuth Implementation
Duration: 3 days
- Implement
GmailOAuthManager- Authorization URL generation
- Endpoint:
https://accounts.google.com/o/oauth2/auth
- Endpoint:
- Code exchange for tokens
- Endpoint:
https://oauth2.googleapis.com/token
- Endpoint:
- Token refresh logic
- Endpoint:
https://oauth2.googleapis.com/token
- Endpoint:
- Token revocation
- Endpoint:
https://oauth2.googleapis.com/revoke
- Endpoint:
- Authorization URL generation
- Implement
GmailServiceAccountAuth- Load service account credentials
- Domain-wide delegation support
- User impersonation
- Create token storage abstraction
- Secure storage interface
- File-based implementation (encrypted)
- Encryption at rest (AES-256)
- Write unit tests for OAuth
- Test authorization URL generation
- Test token exchange
- Test token refresh
- Test error handling
1.4 Rate Limiting
Duration: 2 days
- Implement
TokenBucketclass- Async support
- Configurable rate and burst
- Token refill logic
- Implement
GmailRateLimiter- Per-operation rate limits
- Default: 250 req/100s per user
- Send: 100 req/100s (conservative)
- Batch: 50 req/100s
- Implement daily quota tracker
- Track sends per day (limit: 2000)
- Track queries per day
- Warning on approaching limits (80%)
- Write unit tests
- Test rate limiting behavior
- Test quota tracking
Phase 2: API Integration
2.1 Gmail API Client
Duration: 3 days
- Implement
GmailAPIClient- Base URL:
https://gmail.googleapis.com/gmail/v1 - Authenticated requests via google-api-python-client
- Response handling and error mapping
- Rate limit header parsing
- Base URL:
- Implement message operations
-
send_message()→POST /users/me/messages/send -
get_message()→GET /users/me/messages/{id} -
list_messages()→GET /users/me/messages -
modify_message()→POST /users/me/messages/{id}/modify -
trash_message()→POST /users/me/messages/{id}/trash -
delete_message()→DELETE /users/me/messages/{id}
-
- Implement thread operations
-
get_thread()→GET /users/me/threads/{id} -
list_threads()→GET /users/me/threads
-
- Implement label operations
-
list_labels()→GET /users/me/labels -
create_label()→POST /users/me/labels
-
- Write unit tests
2.2 Email Composer
Duration: 2 days
- Implement
EmailComposer- Build MIME messages
- Plain text body
- HTML body (multipart/alternative)
- Attachments (multipart/mixed)
- Inline images (Content-ID)
- Reply threading (In-Reply-To, References)
- Base64url encoding for Gmail API
- Write unit tests
2.3 Email Parser
Duration: 2 days
- Implement
EmailParser- Parse Gmail API response →
EmailMessage - Parse headers
- Parse addresses
- Extract body (plain + HTML)
- Extract attachments
- Parse dates
- Parse Gmail API response →
- Implement thread parsing
- Parse thread response →
EmailThread - Extract participants
- Parse thread response →
- Write unit tests
2.4 Gmail Provider
Duration: 2 days
- Implement
GmailProvider(EmailProviderInterface)- Implement all interface methods
- Coordinate auth, API client, rate limiter
- Handle authentication modes (OAuth vs Service Account)
- Create configuration loader
- YAML configuration parsing
- Environment variable support
- Validation
- Write integration tests
- Test full send/receive workflow
- Test error scenarios
Phase 3: Push Notifications
3.1 Inbox Watcher
Duration: 3 days
- Implement
GmailInboxWatcher- Gmail watch API integration
- Endpoint:
POST /users/me/watch
- Endpoint:
- Pub/Sub subscriber setup
- History API for message retrieval
- Endpoint:
GET /users/me/history
- Endpoint:
- Gmail watch API integration
- Implement notification handling
- Parse Pub/Sub message
- Fetch new messages via history
- Route to registered handlers
- Implement watch renewal
- Track watch expiration (7 days)
- Automatic renewal before expiry
- Stop watch cleanup
- Endpoint:
POST /users/me/stop
- Endpoint:
- Write unit tests
3.2 Polling Fallback
Duration: 1 day
- Implement
PollingFallback- Configurable poll interval
- Track seen message IDs
- Same handler interface as push
- Automatic fallback on Pub/Sub failure
- Write unit tests
Phase 4: Template System
4.1 Email Template Engine
Duration: 2 days
- Implement
EmailTemplateEngine- Jinja2 integration
- Default templates (meeting invitation, reminder, cancellation)
- Custom template registration
- Template caching
- Create default templates
-
meeting_invitation.html -
meeting_reminder.html -
meeting_cancellation.html -
meeting_update.html
-
- Write unit tests
Phase 5: Integration-Core Email Modules
5.1 Email Interface in integration-core
Duration: 2 days
- Create
coditect_integrations/email/module-
interface.py- EmailProviderInterface -
orchestrator.py- EmailOrchestrator -
exceptions.py- Email exceptions
-
- Add email models to
coditect_integrations/models/-
email.py- EmailMessage, EmailThread, Attachment
-
5.2 Notification Channel Integration
Duration: 2 days
- Create
GmailNotificationChannel(NotificationChannel)- Implement
send()method - Template rendering for meeting notifications
- Implement
- Register with
ReminderService-
ReminderService(email_service=GmailNotificationChannel())
-
- Register with
AttendeeManager-
AttendeeManager(notification_service=GmailNotificationService())
-
5.3 Meeting Provider Integration
Duration: 2 days
- Implement
EmailOrchestratormeeting methods-
send_meeting_invitation(meeting, attendees) -
send_meeting_reminder(meeting, attendee) -
send_meeting_cancellation(meeting, attendees) -
send_meeting_update(meeting, attendees, changes)
-
- Connect to Google Meet provider
- Connect to Zoom provider
- Write integration tests
Phase 6: AI Pipeline Integration
6.1 Email Analysis
Duration: 2 days
- Implement
EmailAnalyzer- Thread analysis for action items
- Sentiment analysis
- Summary generation
- Meeting follow-up detection
- Create AI prompt templates
- Summarization prompt
- Action items extraction prompt
- Decision extraction prompt
- Connect to CODITECT AI service
- Write integration tests
6.2 Context Database Integration
Duration: 2 days
- Implement
EmailContextStore- Store email metadata
- Store thread summaries
- Store AI-generated insights
- Create search capabilities
- Full-text search on emails
- Filter by date range
- Filter by sender/recipient
- Filter by related meeting
- Write integration tests
Phase 7: Testing & Documentation
7.1 Comprehensive Testing
Duration: 3 days
- Unit tests (80%+ coverage)
- OAuth tests
- Rate limiter tests
- API client tests
- Composer tests
- Parser tests
- Provider tests
- Template tests
- Integration tests
- End-to-end send/receive
- Push notification flow
- Error handling scenarios
- Performance tests
- Rate limiting effectiveness
- Response times
7.2 Documentation
Duration: 2 days
- Complete SDD (done)
- Complete TDD (done)
- Complete ADRs (done)
- Create user guide
- GCP setup instructions
- OAuth configuration
- Pub/Sub setup
- Troubleshooting guide
- Create API reference
- Python API documentation
- Code examples
- Update README.md
- Quick start
- Feature list
- Requirements
7.3 Component Activation
Duration: 1 day
- Create component activation entry
- Add to
component-activation-status.json - Define dependencies
- Set default to disabled
- Add to
- Create activation script
- Validate GCP project
- Validate OAuth credentials
- Validate Pub/Sub setup
- Test connectivity
7.4 Final Review
Duration: 1 day
- Code review
- Documentation review
- Security review
- Performance review
- Final testing
GCP Permissions Summary
Required IAM Roles
| Role | Purpose |
|---|---|
roles/pubsub.publisher | Publish to Pub/Sub (for Gmail push) |
roles/pubsub.subscriber | Subscribe to Pub/Sub notifications |
roles/iam.serviceAccountUser | Use service account (if applicable) |
Required OAuth Scopes
| Scope | Purpose |
|---|---|
gmail.send | Send emails |
gmail.readonly | Read emails |
gmail.modify | Modify labels, mark read |
gmail.labels | Manage labels |
API Endpoints Summary
| Operation | Endpoint |
|---|---|
| Send Email | POST https://gmail.googleapis.com/gmail/v1/users/me/messages/send |
| Get Message | GET https://gmail.googleapis.com/gmail/v1/users/me/messages/{id} |
| List Messages | GET https://gmail.googleapis.com/gmail/v1/users/me/messages |
| Get Thread | GET https://gmail.googleapis.com/gmail/v1/users/me/threads/{id} |
| Start Watch | POST https://gmail.googleapis.com/gmail/v1/users/me/watch |
| Stop Watch | POST https://gmail.googleapis.com/gmail/v1/users/me/stop |
| List History | GET https://gmail.googleapis.com/gmail/v1/users/me/history |
| List Labels | GET https://gmail.googleapis.com/gmail/v1/users/me/labels |
| OAuth Token | POST https://oauth2.googleapis.com/token |
| OAuth Revoke | POST https://oauth2.googleapis.com/revoke |
Resource Requirements
Team
- 1 Backend Engineer (primary)
- 0.5 DevOps Engineer (GCP setup)
- 0.25 Tech Writer (documentation review)
Infrastructure
- Google Cloud Project (free tier)
- Cloud Pub/Sub topic and subscription
- CI/CD pipeline (existing)
- Test environment (existing)
Dependencies
[project.dependencies]
coditect-integrations = ">=1.0.0"
[project.optional-dependencies]
gmail = [
"coditect-integrations[google]>=1.0.0",
"google-auth>=2.0.0",
"google-auth-oauthlib>=1.0.0",
"google-api-python-client>=2.0.0",
"google-cloud-pubsub>=2.0.0",
"jinja2>=3.0.0",
"aiofiles>=23.0.0",
"cryptography>=41.0.0",
]
Risk Assessment
| Risk | Probability | Impact | Mitigation |
|---|---|---|---|
| API rate limits hit | Medium | Low | Token bucket rate limiting |
| OAuth token expiry | Low | Medium | Automatic refresh logic |
| Pub/Sub notification missed | Low | Medium | Polling fallback |
| Daily send quota hit | Medium | Medium | Quota tracking, alerts |
| Google API changes | Low | High | Version pinning, monitoring |
| Workspace required for delegation | N/A | N/A | Document requirement clearly |
Success Metrics
| Metric | Target |
|---|---|
| Unit test coverage | 80%+ |
| Integration test pass rate | 100% |
| API response time (p95) | <500ms |
| Push notification latency | <5s |
| Documentation completeness | 100% |
| Zero external costs | Verified |
Acceptance Criteria
MVP (Minimum Viable Product)
- GCP project configured with all APIs enabled
- Can authenticate with Gmail OAuth
- Can send email via Gmail API
- Can receive/read emails
- Push notifications working
- Component activation works
- Documentation complete
Full Release
- All MVP criteria met
- Template system working
- AI analysis integration
- Meeting provider integration
- Context database storage
- Performance targets met
- Security review passed
Integration-Core Components Reference
Core Imports
# Email Provider Interface
from coditect_integrations.email import EmailProviderInterface, EmailOrchestrator
# Models
from coditect_integrations.models import (
EmailMessage, EmailThread, Attachment, EmailLabel,
EmailAnalysis,
)
# Notification Channel
from coditect_integrations.notifications import GmailNotificationChannel
Provider Usage
from google_mail import GmailProvider, GmailOAuthManager
# Initialize
auth = GmailOAuthManager(
client_id=os.environ['GMAIL_CLIENT_ID'],
client_secret=os.environ['GMAIL_CLIENT_SECRET'],
)
provider = GmailProvider(auth_manager=auth)
# Send email
message = await provider.send_email(
to=['recipient@example.com'],
subject='Meeting Invitation',
body='Join us for a meeting...',
html_body='<h1>Meeting Invitation</h1>...',
)
# Watch inbox
watch_id = await provider.watch_inbox(
callback=handle_new_email,
label_ids=['INBOX'],
)
Document Control:
- Created: December 17, 2025
- Owner: CODITECT Engineering Team
- Review Cycle: Weekly during development