# Start a workflow from Gmail events

> Run a workflow when a Gmail mailbox changes, with a Webhook block set to Gmail and a Google Cloud Pub/Sub push subscription.

To run a workflow when a Gmail mailbox changes, add a **Webhook** block whose **Source** is **Gmail** and make its URL the endpoint of a Google Cloud Pub/Sub push subscription. Gmail publishes a notification to a Pub/Sub topic, and the subscription posts it to the block. Each notification starts its own run.

A notification says only that the mailbox changed, and gives the mailbox's new history id. It holds no message. The run asks Gmail what changed with an HTTP request block.

You need the Google Cloud project that owns the OAuth client you call Gmail with, and permission in it to create Pub/Sub topics and subscriptions and to use a service account. You also need a way to call the Gmail API as the mailbox's Google Account, and edit access to the workflow's project.

## Add the Webhook block and generate its URL

1. In a draft workflow, add a **Webhook** block. The block palette also lists **Gmail webhook** in the **Start** group, which adds the block with its source already set.
2. Under **Source**, choose **Gmail**. The line under the setting reads "Verifies the sender's signed token · one run per event · skips duplicates".
3. Under **Webhook URL**, select **Generate URL**, then copy the URL.

The badge beside the URL reads "Runs start after publish". The URL contains a token, and anyone who has the URL can send requests to it. Keep it out of shared documents.

## Create the topic and let Gmail publish to it

1. In Google Cloud, create a Pub/Sub topic. Create it in the project of the OAuth client that will call Gmail's `watch` method. Gmail does not accept a topic in another project.
2. On the topic, grant the Pub/Sub Publisher role to `gmail-api-push@system.gserviceaccount.com`. That is the account Gmail publishes with.

The topic's full name has the form `projects/<project id>/topics/<topic>`. Keep it for the `watch` call.

Google's documentation says a domain-restricted sharing policy can prevent the grant, and that an exception for this account resolves it.

## Create the push subscription

1. In the Google Cloud console, go to the Subscriptions page and click **Create subscription**.
2. In **Subscription ID**, enter a name, and select the topic you created.
3. For **Delivery type**, select **Push**.
4. In **Endpoint URL**, paste the URL you copied.
5. Select **Enable authentication**, and choose a service account in the **Service account** list.
6. Leave **Audience** empty.
7. Leave **Enable payload unwrapping** off, and create the subscription.

With **Audience** empty, Google makes each token for the endpoint URL, and the block accepts only a token made for its own URL. If the subscription has an audience of its own, or its endpoint differs from the block's URL by any character, the block refuses every delivery.

The block reads the wrapper Pub/Sub puts around a message. With payload unwrapping on, the notification arrives without it: `{{input.body.message}}` is empty and duplicates are not skipped.

Google's documentation says Pub/Sub's own service account in the project needs the Service Account Token Creator role, so that it can make tokens for the account you chose.

Pub/Sub does not check the URL when you create the subscription. Nothing arrives until Gmail publishes a notification.

## Save the service account email

With authentication on, Pub/Sub sends each request with a token that Google signs. The token names the service account you chose and the URL the request is for. Google signs such a token for anyone's subscription, so the signature alone does not show that a request is yours. The service account's address does. OutWin compares it with the one saved on the block.

1. In Google Cloud, copy the email address of the service account you chose for the subscription.
2. In OutWin, paste it into **Service account email** in the block's settings and select **Save**.

What you save is an address, not a password. Google issues no secret for a push subscription.

After you save, the settings show only the last four characters of the address. **Replace** and **Remove** appear beside them. Under **Set up**, the second line changes to "The service account email is saved: deliveries are verified."

OutWin saves the address on the block's URL. It is not saved on a connection. A second Webhook block has its own URL and needs its own subscription.

Without a saved address the block still starts runs, and nothing is verified: anyone who has the URL can start the workflow. Publishing then shows a warning that ends "has no signing secret saved, so its deliveries are not verified: anyone who has this URL can start this workflow". The warning does not block publishing.

The token says who is calling and for which URL. It does not cover the message's body, and Google says a token may be up to an hour old. Someone who captured one request could send other bodies with its token until the token expires. A notification holds only a mailbox address and a history id, and the run reads from Gmail with the workflow's own connection, so such a run reads only what that connection can read.

## Start the watch and renew it

1. Send a `POST` request to `https://gmail.googleapis.com/gmail/v1/users/me/watch`, as the mailbox's account.
2. In the request body, set `topicName` to the topic's full name.
3. To hear only about some labels, set `labelIds`.

For example, this body watches the `INBOX` label:

```json
{
  "topicName": "projects/<project id>/topics/<topic>",
  "labelIds": ["INBOX"]
}
```

Gmail answers with a `historyId` and an `expiration`. Keep the `historyId`: it is where the first listing of changes starts. Google's documentation says a successful call sends one notification at once, so the first request reaches the block right after it.

A watch ends unless `watch` is called again at least every seven days, and Google's documentation says to call it once a day. OutWin does not call it. When a watch ends, Gmail publishes nothing and no run starts.

Send the call from any tool that can call the Gmail API as that account, on a schedule of your own. A workflow that starts from a **Schedule** block and calls `watch` with an HTTP request block is one way, within the limit on its credential described under [Read the notification and fetch the changes](https://outwin.ai/docs/build/connect-an-api/start-a-workflow-from-gmail-events/#read-the-notification-and-fetch-the-changes).

## Choose which notifications start a run

Gmail's notification has no event type. Under **Events that start a run**, the settings read "Every request starts a run: Gmail sends no event type to choose by." You choose which changes produce a notification with `labelIds` in the `watch` call, on Gmail's side.

To start runs for only some notifications, add a row under **Only when**. For example, a row with the field `body.message.data.emailAddress` starts runs for one mailbox only. A notification that fails a row is listed as **Filtered out** and starts no run. [Webhook settings](https://outwin.ai/docs/reference/triggers-approvals-and-waits/#webhook-settings) lists the comparisons.

## Send a test and check what arrived

1. Call `watch`, or send a message to the mailbox when a watch is already running.
2. In OutWin, look under **Recent deliveries** in the block's settings.

**Recent deliveries** lists every notification that reached the URL, including while the workflow is a draft. On a draft each is listed as **Dropped** with "The workflow is not published, so nothing ran." It starts no run and is not run later. Under **Set up**, the last line changes from "Waiting for the first event…" to "Received an event. Dropped."

With an address saved, a notification listed as **Dropped** on a draft has passed the check. A request that fails the check is listed as **Refused**, and the last line under **Set up** starts "The last delivery was refused."

If you have edit access, select a notification to see what the block passed on. The list is kept for seven days, and the data of the newest 20 events is kept.

## Read the notification and fetch the changes

Each run receives one notification. An HTTP request block or a database block directly after the Webhook block reads it with these expressions. An AI block such as **Think** receives the whole value as its input.

| Expression | What it holds |
| --- | --- |
| `{{input.body}}` | The request as Pub/Sub sent it, with the fields `message` and `subscription`. Pub/Sub sends `message.data` encoded as base64, and OutWin decodes it. |
| `{{input.body.message.data.emailAddress}}` | The address of the mailbox that changed. |
| `{{input.body.message.data.historyId}}` | The mailbox's history id after the change. |
| `{{input.event.type}}` | Empty. A notification says only that the mailbox changed. |
| `{{input.event.id}}` | The id Pub/Sub gave the message. It is the `message.messageId` field. |
| `{{input.event.time}}` | The message's publish time as an ISO 8601 date and time. It is the `message.publishTime` field. |
| `{{input.delivery.verified}}` | `true` only when the token was checked and passed. |

A block further along reads the same values through the Webhook block's name, as in `{{steps["Gmail"].body.message.data.historyId}}` for a block named `Gmail`. [Data and context](https://outwin.ai/docs/reference/data-and-context/) describes what each block passes on.

To get the changes, add an [HTTP request](https://outwin.ai/docs/reference/blocks/http-request/) block after the Webhook block. It needs an [API connection](https://outwin.ai/docs/build/connect-an-api/) whose credential Google accepts for that account. OutWin does not sign in to Google and does not refresh an access token. A Google access token expires after about an hour, so you need your own way to supply a current one, for example a service of your own in front of Google's API.

Set the block to send a `GET` request to `/gmail/v1/users/me/history`, under the host `https://gmail.googleapis.com`, with the query parameter `startHistoryId`. Gmail lists the changes that came after that id. Pass the history id the workflow stored last, starting with the one the `watch` call returned. The id in the notification is the mailbox's newest, so a listing that starts from it holds nothing of the change that caused the notification.

Keep the newest history id between runs, for example in a database. Notifications can arrive out of order or more than once. Replace the stored id only with a larger one, and never move it backwards. Google's reference says a history id that is too old is answered with status `404`, and that the mailbox then has to be read in full.

## Publish and check the runs

[Publish the workflow](https://outwin.ai/docs/run/publish-and-start/). From then on, each notification that passes the filter starts a run. On a published workflow the block's settings are read-only, and **Recent deliveries** is in the block's inspector. You can still replace the address there.

| Outcome | What happened |
| --- | --- |
| **Ran** | The notification started a run. |
| **Waiting** | 10 runs of the workflow are already active. The notification starts a run when one of them ends. A notification that waits longer than an hour is listed as **Dropped**. |
| **Duplicate** | A notification with the same Pub/Sub message id already ran in the last 72 hours. The line reads "This event was already received and run, so it did not run again." |

Google's documentation says a notification can be delayed or dropped, and that Gmail sends at most one per second for a mailbox. A change with no notification starts no run. The next run that lists the history from the stored id still reads it.

Receiving a notification costs no credits, and neither does one that is filtered out or a duplicate. A run that starts uses credits for the blocks that run in it.

## If nothing runs

Open **Recent deliveries** and read the outcome and the sentence beside the newest notification.

| What you see | Cause | Fix |
| --- | --- | --- |
| "Nothing has arrived yet." | No request has reached the URL. The `watch` call failed, the topic is not the one the subscription reads, or the subscription's endpoint is not the block's current URL. | Read the answer to the `watch` call, and check the subscription's topic and **Endpoint URL**. **Rotate token** on a published workflow changes the URL, and the old one stops working: change the subscription's endpoint to the new one. |
| Notifications arrived for some days and then stopped | The watch ended because `watch` was not called again within seven days. | Call `watch` again, and call it on a schedule from then on. |
| **Dropped** with "The workflow is not published, so nothing ran." | The workflow is a draft. | Publish the workflow. Notifications that arrived before then are not run later. |
| **Dropped** with "The workflow is paused, so nothing ran." | The workflow is paused. | Resume the workflow. Notifications that arrived while it was paused are not run later. |
| **Refused** with "The request carried no signed token. Turn on authentication in the push subscription and choose a service account." | An address is saved in OutWin, and the request carried no token. The subscription has authentication off, or the request was sent by hand to try the URL. | Edit the subscription, select **Enable authentication**, and choose the service account whose address is saved. |
| **Refused** with "The request's token was made for a different URL. The subscription's endpoint must be this block's URL exactly as shown, and its audience left empty." | The subscription has an **Audience** set, or its **Endpoint URL** is not the block's URL character for character. Another host, an added query string, or an added trailing slash each make it a different URL. | In the subscription, clear **Audience**. Copy the URL from the block again and paste it as the **Endpoint URL** with nothing added. |
| **Refused** with "The request's token is for a different service account than the one saved here." | The subscription uses another service account than the one whose address is saved. | Select **Replace** and save the address of the subscription's service account. You do not republish the workflow. |
| **Refused** with "The saved service account email is not an email address. Save it again exactly as Google Cloud shows it." | Something other than the address was pasted. | Copy the service account's email address again and select **Replace**. |
| **Refused** with "The key that signed the request's token could not be fetched, so it could not be checked." | OutWin could not fetch Google's signing keys. | Wait for Pub/Sub to send the notification again. |

A request whose token Google did not sign, or whose token has expired, is also listed as **Refused**, with a sentence that starts "The request's token".

A request listed as **Refused** is answered with status `401` and starts nothing. OutWin keeps none of its data. Pub/Sub sends a notification that was not accepted again, so a subscription that is set up wrongly shows as one **Refused** line after another. After you correct it, a later attempt of the same notification can pass and start a run. For every other outcome in the table, Pub/Sub receives a success response and OutWin does not run the notification later.
