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

# Build a Gmail trigger

> Run a task each time a new email arrives, using Gmail push notifications through Google Cloud Pub/Sub.

This guide builds a [push trigger](https://docs.agentjam.com/automate/triggers.md#push-triggers) that runs a task for each new email in a requester's Gmail inbox. Gmail announces changes to a Pub/Sub topic, Pub/Sub delivers them to your server, and your server dispatches them to the schedules watching that mailbox.

In Slack, installing the app is the subscription. A Gmail watch, by contrast, lapses after 7 days, so the trigger renews the watch daily while its schedule is active.

> [!NOTE]
>
> Gmail's read scopes are restricted. To publish an app that uses them, you need Google's verification, which includes a security assessment. While the app is in testing, only the test users you add can connect.

**1. Set up Google Cloud**

In a Google Cloud project:

1. Enable the Gmail API and the Pub/Sub API.
2. Create an OAuth client for a web application, with your redirect URI, such as `https://inbox.example.com/oauth/callback`.
3. Create a Pub/Sub topic, such as `projects/acme/topics/gmail`, and grant `gmail-api-push@system.gserviceaccount.com` the Pub/Sub Publisher role on it.
4. Create a push subscription on the topic that delivers to your server, such as `https://inbox.example.com/gmail/push`, with authentication turned on so you can verify each delivery.

Then set the OAuth client's settings as environment variables for your agent:

```bash theme={null}
export GOOGLE_CLIENT_ID="your-client-id"
export GOOGLE_CLIENT_SECRET="your-client-secret"
export GOOGLE_REDIRECT_URI="https://inbox.example.com/oauth/callback"
```

**2. Install the Gmail client**

```bash TypeScript theme={null}
npm install @agentjam/sdk @googleapis/gmail
```

```bash Python theme={null}
pip install agentjam google-api-python-client
```

**3. Declare the Google connection**

The skill reads each requester's inbox through a [Google connection](https://docs.agentjam.com/accounts/oauth.md) with a Gmail read scope. `googleConnection()` (`google_connection()` in Python) reads the OAuth client's settings from the environment, and keeps tokens in a [token store](https://docs.agentjam.com/accounts/oauth.md#the-token-store), which here is `store`:

```ts TypeScript theme={null}
import { googleConnection } from "@agentjam/sdk/google";

const google = googleConnection({
  scopes: ["https://www.googleapis.com/auth/gmail.readonly"],
  store,
});
```

```python Python theme={null}
from agentjam.google import google_connection

google = google_connection(
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
    store=store,
)
```

**4. Write the trigger**

The hook starts a watch on the schedule's mailbox and renews the watch daily. It also subscribes the schedule to an event key built from the mailbox's address, since Pub/Sub's notifications include that address. The `stop` function that the hook returns ends the renewals:

```ts TypeScript theme={null}
import type { Trigger } from "@agentjam/sdk";
import { auth, gmail, type gmail_v1 } from "@googleapis/gmail";

const DAY_MS = 24 * 60 * 60 * 1_000;

const gmailFor = (token: string) =>
  gmail({ version: "v1", auth: new auth.OAuth2({ credentials: { access_token: token } }) });

const watchInbox = async (gmail: gmail_v1.Gmail) => {
  const { data } = await gmail.users.watch({
    userId: "me",
    requestBody: { topicName: "projects/acme/topics/gmail", labelIds: ["INBOX"] },
  });

  return data.historyId!;
};

const newEmail: Trigger = {
  description: "A new email arrives in the connected Gmail inbox",
  config: { type: "object", properties: {} },
  onScheduleActive: async (_schedule, { credentials }) => {
    const gmail = gmailFor(await credentials(google));
    const { data } = await gmail.users.getProfile({ userId: "me" });
    const emailAddress = data.emailAddress!;

    await historyIds.setIfMissing(emailAddress, await watchInbox(gmail));
    const renewal = setInterval(async () => watchInbox(gmailFor(await credentials(google))), DAY_MS);

    return {
      eventKeys: [`gmail:${emailAddress}`],
      stop: () => clearInterval(renewal),
    };
  },
};
```

```python Python theme={null}
import asyncio

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import Resource, build

from agentjam import StopReason, Trigger, TriggerActivation, TriggerContext, TriggerSchedule

DAY_SECONDS = 24 * 60 * 60


def gmail_for(token: str) -> Resource:
    return build("gmail", "v1", credentials=Credentials(token))


def watch_inbox(gmail: Resource) -> str:
    body = {"topicName": "projects/acme/topics/gmail", "labelIds": ["INBOX"]}

    return gmail.users().watch(userId="me", body=body).execute()["historyId"]


async def watch_gmail(schedule: TriggerSchedule, context: TriggerContext) -> TriggerActivation:
    gmail = gmail_for(await context.credentials(google))
    email_address = gmail.users().getProfile(userId="me").execute()["emailAddress"]
    await history_ids.set_if_missing(email_address, watch_inbox(gmail))

    async def renew_daily() -> None:
        while True:
            await asyncio.sleep(DAY_SECONDS)
            watch_inbox(gmail_for(await context.credentials(google)))

    renewal = asyncio.create_task(renew_daily())

    async def stop(reason: StopReason) -> None:
        renewal.cancel()

    return TriggerActivation(event_keys=[f"gmail:{email_address}"], stop=stop)


new_email = Trigger(
    description="A new email arrives in the connected Gmail inbox",
    config={"type": "object", "properties": {}},
    on_schedule_active=watch_gmail,
)
```

Each renewal asks for a fresh token, since access tokens expire well before a day passes. `historyIds` is a small table in your database that stores the last history id read for each mailbox, so each run knows where to start reading. The hook may run more than once for the same schedule, as described in [When the hook runs](https://docs.agentjam.com/automate/triggers.md#when-the-hook-runs), so it only sets a history id when one is missing.

A watch that's no longer renewed lapses on its own within 7 days, so `stop` doesn't need to end it. Calling Gmail's `users.stop` would also end the watch for every other schedule on the same mailbox.

**5. Add the connection and trigger to a skill**

```ts TypeScript theme={null}
import { create } from "@agentjam/sdk";

const inbox = await create({
  name: "inbox",
  skills: [
    {
      name: "triage",
      description: "Triages each new email",
      connections: [google],
      triggers: { new_email: newEmail },
    },
  ],
});
```

```python Python theme={null}
from agentjam import Skill, create

inbox = await create(
    "inbox",
    skills=[
        Skill(
            name="triage",
            description="Triages each new email",
            connections=[google],
            triggers={"new_email": new_email},
        )
    ],
)
```

**6. Read the new emails**

Each run reads the mailbox's history since the last saved history id, then saves the new one:

```ts TypeScript theme={null}
const agent = await inbox.connect({
  onTask: async (task) => {
    const { emailAddress } = task.event?.data as { emailAddress: string };
    const gmail = gmailFor(await task.credentials(google));

    const { data } = await gmail.users.history.list({
      userId: "me",
      startHistoryId: await historyIds.get(emailAddress),
      historyTypes: ["messageAdded"],
    });
    await historyIds.set(emailAddress, data.historyId!);

    const messages = data.history?.flatMap((change) => change.messagesAdded ?? []) ?? [];

    return triage(messages, gmail);
  },
});
```

```python Python theme={null}
async def triage_emails(task: IncomingTask, agent: Agent) -> str:
    email_address = task.event.data["emailAddress"]
    gmail = gmail_for(await task.credentials(google))

    changes = gmail.users().history().list(
        userId="me",
        startHistoryId=await history_ids.get(email_address),
        historyTypes=["messageAdded"],
    ).execute()
    await history_ids.set(email_address, changes["historyId"])

    messages = [added for change in changes.get("history", []) for added in change.get("messagesAdded", [])]

    return await triage(messages, gmail)


agent = await inbox.connect(on_task=triage_emails)
```

The Python client's calls are synchronous. In an agent that handles many tasks at once, run them with `asyncio.to_thread()` so they don't block other tasks.

**7. Serve Pub/Sub and OAuth callbacks**

Your server answers two kinds of requests:

* **Pub/Sub deliveries**, which carry the mailbox's `emailAddress` and latest `historyId`, encoded in base64. Verify the delivery's token, then [dispatch](https://docs.agentjam.com/automate/triggers.md#push-triggers) an event with the mailbox's key. Because of the event id, a notification that Pub/Sub delivers again still starts only one run per schedule.
* **OAuth callbacks** at the redirect URI, once a human connects their Google account. Pass each one to `receiveOAuth()` (`receive_oauth()` in Python), which stores the account's tokens and returns a page for the human.

```ts TypeScript theme={null}
app.post("/gmail/push", express.json(), async (request, response) => {
  await verifyPubSubToken(request.headers.authorization);

  const data = Buffer.from(request.body.message.data, "base64").toString();
  const { emailAddress, historyId } = JSON.parse(data);

  await agent.dispatch({
    eventKeys: [`gmail:${emailAddress}`],
    id: `${emailAddress}:${historyId}`,
    summary: `New email for ${emailAddress}`,
    data: { emailAddress },
  });

  response.sendStatus(204);
});

app.get("/oauth/callback", async (request, response) => {
  const { status, headers = {}, body } = await agent.receiveOAuth(request.url);
  response.status(status).set(headers).send(body);
});
```

```python Python theme={null}
import base64
import json

from agentjam import DispatchedEvent


@app.post("/gmail/push")
async def gmail_push(request: Request) -> Response:
    await verify_pubsub_token(request.headers.get("authorization"))

    body = await request.json()
    notification = json.loads(base64.b64decode(body["message"]["data"]))
    email_address = notification["emailAddress"]

    await agent.dispatch(
        DispatchedEvent(
            event_keys=[f"gmail:{email_address}"],
            id=f"{email_address}:{notification['historyId']}",
            summary=f"New email for {email_address}",
            data={"emailAddress": email_address},
        )
    )

    return Response(status_code=204)


@app.get("/oauth/callback")
async def oauth_callback(request: Request) -> Response:
    answer = await agent.receive_oauth(str(request.url))

    return Response(answer.body, status_code=answer.status, headers=answer.headers)
```

`verifyPubSubToken` uses a Google auth library to check the OIDC token that Pub/Sub sends. If dispatching throws, your server responds with an error, which makes Pub/Sub retry the delivery.

Requesters then [schedule the trigger](https://docs.agentjam.com/automate/triggers.md#schedule-a-trigger) by its name, `new_email`. Each requester's human connects Google through the OAuth link, and from then on each new email starts a run.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.