Gmail API

Endpoints for Gmail integration - create email drafts from Archivus content.


Overview

The Gmail API allows authenticated users to:

  • Connect their Gmail account via OAuth
  • Create email drafts from Archivus content
  • Reply to email threads with AI-generated content

OAuth Flow

Get Authorization URL

Get the OAuth URL to redirect users for Gmail authorization.

GET /gmail/auth-url

Query Parameters:

Parameter Type Required Description
redirect_url string No Custom redirect URL after OAuth (defaults to Settings page)

Response:

{
  "auth_url": "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=...&scope=...&state=abc123",
  "state": "abc123"
}

Usage:

  1. Redirect user to auth_url
  2. User signs in and grants permissions
  3. User is redirected back to Archivus with auth code
  4. Archivus exchanges code for tokens automatically

OAuth Callback

OAuth callback endpoint (handled automatically by Archivus).

GET /gmail/callback

Query Parameters:

Parameter Type Description
code string OAuth authorization code
state string OAuth state for CSRF protection
error string OAuth error (if authorization failed)

Behavior:

  • On success: Redirects to Settings with ?success=true
  • On error: Redirects to Settings with error details

Connection Management

Get Connection Status

Check if the user has connected their Gmail account.

GET /gmail/connection

Response (Connected):

{
  "connected": true,
  "connection": {
    "id": "conn_abc123",
    "gmail_email": "user@gmail.com",
    "is_active": true,
    "connected_at": "2024-01-15T10:30:00Z",
    "last_used_at": "2024-01-20T14:22:00Z"
  }
}

Response (Not Connected):

{
  "connected": false
}

Disconnect Gmail

Remove the Gmail connection and delete stored tokens.

DELETE /gmail/connection

Response:

{
  "message": "Gmail disconnected successfully"
}

Error Responses:

Status Code Description
400 NOT_CONNECTED Gmail not connected for this user

Draft Creation

Create Draft

Create a draft email in the user’s Gmail account.

POST /gmail/draft

Request Body:

{
  "content": "# Document Summary\n\nHere are the key findings...",
  "to": ["recipient@example.com"],
  "cc": ["manager@example.com"],
  "subject": "Document Analysis Results"
}

Request Parameters:

Parameter Type Required Description
content string Yes Email body content (Markdown supported)
to array No Recipient email addresses
cc array No CC recipient email addresses
subject string No Email subject line
reply_to_id string No Gmail thread ID for replies

Response:

{
  "draft_id": "r1234567890",
  "message_id": "1234567890abcdef",
  "gmail_url": "https://mail.google.com/mail/#drafts/1234567890abcdef",
  "message": "Draft created successfully"
}

Error Responses:

Status Code Description
400 NOT_CONNECTED Gmail not connected
400 INACTIVE Gmail connection is inactive, needs reconnection
400 INVALID_EMAIL One or more email addresses are invalid
500 DRAFT_FAILED Failed to create draft in Gmail

Create Reply Draft

Create a draft that replies to an existing email thread.

POST /gmail/draft

Request Body:

{
  "content": "Based on my analysis of the attached documents, I recommend...",
  "reply_to_id": "thread_abc123def"
}

The draft will be created as a reply in the specified thread, maintaining conversation context.


Content Formatting

Markdown Support

The content field supports Markdown, which is converted to HTML for the email:

Markdown Result
# Heading <h1>Heading</h1>
**bold** <strong>bold</strong>
*italic* <em>italic</em>
- item Bulleted list
1. item Numbered list
[link](url) Clickable hyperlink
`code` Inline code
```code``` Code block

Example:

# Summary Report

## Key Findings

1. **Revenue growth** increased by 15%
2. Customer satisfaction at *all-time high*

### Recommendations

- Expand marketing efforts
- Consider new product line

[View full report](https://archivus.app/documents/abc123)

Code Examples

Python - Create Draft from Document Summary

import requests

API_BASE = "https://api.archivus.app/api/v1"
API_KEY = "YOUR_API_KEY"

def create_gmail_draft(content, recipients, subject):
    """Create a Gmail draft with the given content."""
    response = requests.post(
        f"{API_BASE}/gmail/draft",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "content": content,
            "to": recipients,
            "subject": subject
        }
    )
    return response.json()

# Example usage
summary = """
# Document Analysis

## Summary
This document contains quarterly financial data showing positive growth.

## Key Points
- Revenue up 15% YoY
- Expenses reduced by 8%
- Net margin improved to 22%

## Recommendation
Continue current strategy with focus on cost optimization.
"""

result = create_gmail_draft(
    content=summary,
    recipients=["team@company.com"],
    subject="Q4 2024 Financial Analysis"
)

print(f"Draft created: {result['gmail_url']}")

JavaScript - Check Connection and Create Draft

async function sendToGmail(content, recipients, subject) {
  const apiKey = 'YOUR_API_KEY';
  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  };

  // Check connection first
  const statusRes = await fetch(
    'https://api.archivus.app/api/v1/gmail/connection',
    { headers }
  );
  const status = await statusRes.json();

  if (!status.connected) {
    // Get auth URL and redirect user
    const authRes = await fetch(
      'https://api.archivus.app/api/v1/gmail/auth-url',
      { headers }
    );
    const { auth_url } = await authRes.json();
    window.location.href = auth_url;
    return;
  }

  // Create draft
  const draftRes = await fetch(
    'https://api.archivus.app/api/v1/gmail/draft',
    {
      method: 'POST',
      headers,
      body: JSON.stringify({
        content,
        to: recipients,
        subject
      })
    }
  );

  const draft = await draftRes.json();

  // Open Gmail with the draft
  window.open(draft.gmail_url, '_blank');
}

// Usage
sendToGmail(
  '# Hello\n\nThis is a test email.',
  ['recipient@example.com'],
  'Test Email'
);

cURL - Complete Flow

# 1. Check connection status
curl -X GET https://api.archivus.app/api/v1/gmail/connection \
  -H "Authorization: Bearer YOUR_API_KEY"

# 2. If not connected, get auth URL
curl -X GET https://api.archivus.app/api/v1/gmail/auth-url \
  -H "Authorization: Bearer YOUR_API_KEY"
# Then redirect user to the auth_url

# 3. Create a draft
curl -X POST https://api.archivus.app/api/v1/gmail/draft \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "# Meeting Notes\n\n- Discussed Q4 targets\n- Agreed on timeline",
    "to": ["team@company.com"],
    "subject": "Meeting Notes - Dec 30"
  }'

# 4. Disconnect when done (optional)
curl -X DELETE https://api.archivus.app/api/v1/gmail/connection \
  -H "Authorization: Bearer YOUR_API_KEY"

Error Handling

Connection Errors

{
  "error": "Gmail not connected. Please connect Gmail in Settings.",
  "code": "NOT_CONNECTED"
}

Solution: Redirect user to OAuth flow.

Inactive Connection

{
  "error": "Gmail connection is inactive. Please reconnect in Settings.",
  "code": "INACTIVE"
}

Solution: Token expired or revoked. User needs to reconnect.

Invalid Email

{
  "error": "Invalid email address: not-an-email",
  "code": "INVALID_EMAIL"
}

Solution: Validate email addresses before sending.


Security Notes

  1. OAuth 2.0 - Standard authorization flow
  2. Minimal scopes - Only compose/draft permission requested
  3. Token encryption - Stored with AES-256-GCM
  4. Auto-refresh - Tokens refreshed automatically
  5. Secure disconnect - All tokens removed on disconnect

Rate Limits

Gmail API operations count toward your Archivus rate limit:

Operation Cost
Get auth URL 1 request
Check connection 1 request
Create draft 1 request
Disconnect 1 request

Endpoints Summary

Endpoint Method Description
/gmail/auth-url GET Get OAuth authorization URL
/gmail/callback GET OAuth callback (automatic)
/gmail/connection GET Get connection status
/gmail/connection DELETE Disconnect Gmail
/gmail/draft POST Create email draft


Questions? Contact support@archivusdms.com