Skip to main content

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

  1. Zero External Cost - Use only free-tier Gmail API quotas
  2. Optional Component - Activatable only when needed
  3. Provider Agnostic - Abstract interface for multi-provider support
  4. CODITECT Native - Follow framework patterns and conventions
  5. 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

  • 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

APIEndpoint BaseDocumentation
Gmail API v1https://gmail.googleapis.com/gmail/v1https://developers.google.com/gmail/api
Cloud Pub/Sub v1https://pubsub.googleapis.com/v1https://cloud.google.com/pubsub/docs
OAuth 2.0https://oauth2.googleapis.comhttps://developers.google.com/identity
Token Infohttps://oauth2.googleapis.com/tokeninfo-
Token Revokehttps://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 .env file 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 .env to .gitignore

  • Create .env.example with 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.toml with dependencies
  • Configure pytest and coverage
  • Set up pre-commit hooks
  • Create .gitignore for secrets

1.2 Email Provider Interface

Duration: 2 days

  • Define EmailProviderInterface abstract 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
  • Create data models
    • EmailMessage dataclass
    • EmailThread dataclass
    • Attachment dataclass
    • EmailLabel dataclass
  • Define exception hierarchy
    • EmailIntegrationError base
    • EmailAuthenticationError
    • EmailRateLimitError
    • EmailNotFoundError
    • EmailSendError

1.3 OAuth Implementation

Duration: 3 days

  • Implement GmailOAuthManager
    • Authorization URL generation
      • Endpoint: https://accounts.google.com/o/oauth2/auth
    • Code exchange for tokens
      • Endpoint: https://oauth2.googleapis.com/token
    • Token refresh logic
      • Endpoint: https://oauth2.googleapis.com/token
    • Token revocation
      • Endpoint: https://oauth2.googleapis.com/revoke
  • 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 TokenBucket class
    • 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
  • 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
  • Implement thread parsing
    • Parse thread response → EmailThread
    • Extract participants
  • 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
    • Pub/Sub subscriber setup
    • History API for message retrieval
      • Endpoint: GET /users/me/history
  • 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
  • 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
  • Register with ReminderService
    • ReminderService(email_service=GmailNotificationChannel())
  • Register with AttendeeManager
    • AttendeeManager(notification_service=GmailNotificationService())

5.3 Meeting Provider Integration

Duration: 2 days

  • Implement EmailOrchestrator meeting 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
  • 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

RolePurpose
roles/pubsub.publisherPublish to Pub/Sub (for Gmail push)
roles/pubsub.subscriberSubscribe to Pub/Sub notifications
roles/iam.serviceAccountUserUse service account (if applicable)

Required OAuth Scopes

ScopePurpose
gmail.sendSend emails
gmail.readonlyRead emails
gmail.modifyModify labels, mark read
gmail.labelsManage labels

API Endpoints Summary

OperationEndpoint
Send EmailPOST https://gmail.googleapis.com/gmail/v1/users/me/messages/send
Get MessageGET https://gmail.googleapis.com/gmail/v1/users/me/messages/{id}
List MessagesGET https://gmail.googleapis.com/gmail/v1/users/me/messages
Get ThreadGET https://gmail.googleapis.com/gmail/v1/users/me/threads/{id}
Start WatchPOST https://gmail.googleapis.com/gmail/v1/users/me/watch
Stop WatchPOST https://gmail.googleapis.com/gmail/v1/users/me/stop
List HistoryGET https://gmail.googleapis.com/gmail/v1/users/me/history
List LabelsGET https://gmail.googleapis.com/gmail/v1/users/me/labels
OAuth TokenPOST https://oauth2.googleapis.com/token
OAuth RevokePOST 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

RiskProbabilityImpactMitigation
API rate limits hitMediumLowToken bucket rate limiting
OAuth token expiryLowMediumAutomatic refresh logic
Pub/Sub notification missedLowMediumPolling fallback
Daily send quota hitMediumMediumQuota tracking, alerts
Google API changesLowHighVersion pinning, monitoring
Workspace required for delegationN/AN/ADocument requirement clearly

Success Metrics

MetricTarget
Unit test coverage80%+
Integration test pass rate100%
API response time (p95)<500ms
Push notification latency<5s
Documentation completeness100%
Zero external costsVerified

Acceptance Criteria

MVP (Minimum Viable Product)

  1. GCP project configured with all APIs enabled
  2. Can authenticate with Gmail OAuth
  3. Can send email via Gmail API
  4. Can receive/read emails
  5. Push notifications working
  6. Component activation works
  7. Documentation complete

Full Release

  1. All MVP criteria met
  2. Template system working
  3. AI analysis integration
  4. Meeting provider integration
  5. Context database storage
  6. Performance targets met
  7. 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