> ## Documentation Index
> Fetch the complete documentation index at: https://docs.upsonic.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Gmail

> Host agents as Gmail email assistants

Use the Gmail interface to serve Agents via Gmail. It mounts API routes on a FastAPI app and enables automated email processing and replies.

## Installation

Install the Gmail interface dependencies:

```bash theme={null}
uv pip install "upsonic[gmail-interface]"
```

## Setup

Required environment variables:

* `GMAIL_API_SECRET` (optional, for endpoint protection)

* Gmail OAuth credentials (via `credentials.json` and `token.json` files)

<Note>
  The interface uses a pull-based model - you manually trigger email checks via the `/gmail/check` endpoint, and the agent processes unread emails.
</Note>

## Operating Modes

* **TASK** (default) – Each email is processed as an independent task; no conversation history. Best for classification, auto-responders, one-off processing.
* **CHAT** – Emails from the same sender share a conversation session. The agent can reference earlier emails. Best for support threads and ongoing conversations.

## Reset Command (CHAT mode only)

In CHAT mode, senders can clear their conversation by including the reset command in the email body (e.g. `/reset`). You configure it with `reset_command`; set to `None` to disable.

If the agent has a `workspace` configured, the reset command will also trigger a dynamic greeting message based on the workspace configuration. See [Workspace](/concepts/agents/advanced/workspace) for details.

## Access Control (Whitelist)

Pass `allowed_emails` (list of email addresses). Only those senders are processed; others receive a fixed "This operation not allowed" response. Omit `allowed_emails` (or set `None`) to allow all senders.

## Example Usage

Create an agent, expose it with the `GmailInterface` interface, and serve via `InterfaceManager`. Example with **CHAT** mode, reset command, and optional whitelist:

```python theme={null}
import os
from upsonic import Agent
from upsonic.interfaces import InterfaceManager, GmailInterface, InterfaceMode

agent = Agent(
    model="anthropic/claude-sonnet-4-6",
    name="EmailAssistant",
)

gmail = GmailInterface(
    agent=agent,
    credentials_path="credentials.json",
    token_path="token.json",
    api_secret=os.getenv("GMAIL_API_SECRET"),
    mode=InterfaceMode.CHAT,
    reset_command="/reset",
    allowed_emails=["support@mycompany.com", "user@example.com"],
)

manager = InterfaceManager(interfaces=[gmail])

if __name__ == "__main__":
    manager.serve(host="0.0.0.0", port=8000, reload=False)
```

## Core Components

* `GmailInterface` (interface): Wraps an Upsonic `Agent` for Gmail via FastAPI.

* `InterfaceManager.serve`: Serves the FastAPI app using Uvicorn.

## `GmailInterface` Interface

Main entry point for Upsonic Gmail applications.

### Initialization Parameters

| Parameter          | Type                        | Default              | Description                                                                     |
| ------------------ | --------------------------- | -------------------- | ------------------------------------------------------------------------------- |
| `agent`            | `Agent`                     | Required             | Upsonic `Agent` instance.                                                       |
| `name`             | `str`                       | `"Gmail"`            | Interface name.                                                                 |
| `credentials_path` | `Optional[str]`             | `None`               | Path to Gmail OAuth credentials.json.                                           |
| `token_path`       | `Optional[str]`             | `None`               | Path to Gmail OAuth token.json.                                                 |
| `api_secret`       | `Optional[str]`             | `None`               | Secret token for API authentication (or set `GMAIL_API_SECRET`).                |
| `mode`             | `Union[InterfaceMode, str]` | `InterfaceMode.TASK` | `TASK` or `CHAT`.                                                               |
| `reset_command`    | `Optional[str]`             | `"/reset"`           | Text in email body that resets chat session (CHAT mode). Set `None` to disable. |
| `storage`          | `Optional[Storage]`         | `None`               | Storage backend for chat sessions (CHAT mode).                                  |
| `allowed_emails`   | `Optional[List[str]]`       | `None`               | Whitelist of sender emails; only these are processed. `None` = allow all.       |

### Key Methods

| Method                     | Parameters        | Return Type           | Description                                                     |
| -------------------------- | ----------------- | --------------------- | --------------------------------------------------------------- |
| `attach_routes`            | None              | `APIRouter`           | Returns the FastAPI router and attaches endpoints.              |
| `check_and_process_emails` | `count: int = 10` | `CheckEmailsResponse` | Manually trigger email check and processing.                    |
| `is_email_allowed`         | `email: str`      | `bool`                | Whether the sender is in the whitelist (or whitelist disabled). |

## Endpoints

Mounted under the `/gmail` prefix:

### `POST /gmail/check`

* Manually triggers a check for unread emails and processes them.

* Query parameter: `count` (default: 3) - maximum number of emails to process.

* Requires `X-Upsonic-Gmail-Secret` header if `GMAIL_API_SECRET` is configured.

* Fetches unread emails, processes each with the agent, sends replies if agent decides to reply, marks emails as read.

* Returns: `200 CheckEmailsResponse` with `status`, `processed_count`, and `message_ids`.

### `GET /gmail/health`

* Health/status of the interface.
