# Webhooks

Receive signed HTTP callbacks for email lifecycle events.

Base URL: `https://api.groundmail.dev`

Manage endpoints in the dashboard (**Webhooks**) or via the API / SDK / CLI below.

To try your handler with real payloads, send to the simulator addresses (`bounce@simulator.groundmail.dev`, `complaint@…` and others) or use a test key: see [Testing](https://docs.groundmail.dev/testing). Simulated events carry `"test": true` in `data`.

---

## Authentication

```http
Authorization: Bearer gm_…
```

Dashboard session cookies also work for browser requests to `/api/webhooks`.

---

## Supported events

| Event | When fired |
|-------|------------|
| `email.received` | An inbound email arrived on a receive-enabled domain; retrieve full content from `/received-emails/{id}` |
| `email.sent` | Groundmail accepted the message for delivery |
| `email.delivered` | The message was delivered to the recipient mailbox provider |
| `email.delivery_delayed` | Delivery was delayed (the receiving server deferred it) |
| `email.held` | The email was held before sending: by [content scanning](https://docs.groundmail.dev/content-scanning#held) (then released or rejected), or while sending is paused on the account. `data.held_reason` says why; `data.spam_score` is set when scanning held it |
| `email.bounced` | The message bounced. `data.bounce_type` is `hard` (address can't receive; recipient is auto-suppressed) or `block` (the receiving server refused the sender; recipient is not suppressed) |
| `email.complained` | Recipient marked the message as spam/complaint |
| `email.opened` | Open pixel loaded when open tracking is on |
| `email.clicked` | Tracked link clicked when click tracking is on |
| `email.failed` | Delivery failed; permanent SMTP failures to a bad address also auto-suppress the recipient and set `data.bounce_type` to `hard`. A refusal for the message's size (`552 5.3.4`) never suppresses and has `data.bounce_type: null`. Also fires when an email the API answered `queued` could not be handed to the mail server: it refused the email, or temporary problems lasted past about 15 minutes of retries. `data.bounce_reason` says why |
| `email.suppressed` | Send blocked because a recipient is on the suppression list |
| `email.scheduled` | Email accepted with `scheduled_at` |
| `contact.unsubscribed` | Recipient completed a managed unsubscribe. `data.scope` is `all` (suppression) or `category` (opt-out of product or newsletter email only). On a tenant's email, `data.tenant` names the tenant and the unsubscribe applies to that tenant only |
| `automation.started` | An active automation matched an incoming event and a run was created |
| `automation.step_completed` | One automation step completed successfully |
| `automation.completed` | A run finished all steps (or ended early on a false condition) |
| `automation.failed` | A run failed (send failure, timeout, validation, etc.) |
| `mailbox.message.received` | A message arrived at one of your [mailboxes](https://docs.groundmail.dev/mailboxes) and wasn't held. A summary without the bodies; everything the sender wrote is untrusted |
| `mailbox.message.sent` | One of your mailboxes sent a message. The same summary, with `data.untrusted: false`. Delivery then shows in the usual `email.*` events |

Open/click tracking are domain settings (`open_tracking` / `click_tracking`) configured per domain. These events only fire once the domain's `tracking_status` is `active` (see [Domains](https://docs.groundmail.dev/domains#tracking-and-tls-preferences)).

---

## Create endpoint

`POST /webhooks`

```json
{
  "url": "https://yourapp.com/webhooks/groundmail",
  "events": ["email.delivered", "email.bounced"]
}
```

`events` is optional — defaults to all supported events.

`url` must be an `http` or `https` URL on a public address, with no username or password in it. Private, internal and loopback addresses are refused with `400 validation_error`.

### 200 — Created

```json
{
  "webhook": {
    "id": "clx…",
    "url": "https://yourapp.com/webhooks/groundmail",
    "events": ["email.delivered", "email.bounced"],
    "enabled": true,
    "created_at": "2026-07-25T12:00:00.000Z",
    "updated_at": "2026-07-25T12:00:00.000Z"
  },
  "secret": "whsec_…"
}
```

Copy `secret` immediately — it is only returned once. Use it to verify incoming webhook signatures.

---

## List endpoints

`GET /webhooks`

Cursor pagination: `limit`, `cursor` → `{ webhooks, has_more, next_cursor }`.

---

## Retrieve endpoint

`GET /webhooks/{id}`

```json
{
  "webhook": {
    "id": "clx…",
    "url": "https://yourapp.com/webhooks/groundmail",
    "events": ["email.delivered", "email.bounced"],
    "enabled": true,
    "created_at": "2026-07-25T12:00:00.000Z",
    "updated_at": "2026-07-25T12:00:00.000Z"
  }
}
```

---

## Update endpoint

`PATCH /webhooks/{id}`

```json
{
  "url": "https://yourapp.com/new-path",
  "events": ["email.bounced"],
  "enabled": false
}
```

All fields are optional.

---

## Tenant filters

If you use [tenants](https://docs.groundmail.dev/tenants), every email event carries `data.tenant` (the tenant's `external_id`), so one endpoint can route events per customer. To send only some tenants' events to an endpoint, set `tenants` on create or update:

```json
{
  "url": "https://acme.example.com/hooks/email",
  "events": ["email.delivered", "email.bounced"],
  "tenants": ["cust_8412"]
}
```

- A filtered endpoint gets only events of those tenants (up to 100 per endpoint): their email events, and `contact.unsubscribed` from their email. It gets no `email.received` or `automation.*` events, and no unsubscribes from email not sent for a tenant, which have no tenant.
- `"tenants": []` or `null` on `PATCH /webhooks/{id}` removes the filter, so the endpoint gets every event again.
- Webhook objects carry `tenants` only when filtered.
- Deleting a tenant removes it from filters. An endpoint left with no tenants is disabled rather than switched to every event.
- Naming a tenant that does not exist is a `404`; `tenants` on an account without tenants (they're on the pay-as-you-go and Dedicated plans) is a `403` `tenants_not_enabled`.

---

## Mailbox filters

To hear only some of your [mailboxes](https://docs.groundmail.dev/mailboxes), set `mailboxes` on create or update, up to 100 per endpoint. Name each by its `mbx_` id, address or `external_id`:

```json
{
  "url": "https://yourapp.com/hooks/mail",
  "events": ["mailbox.message.received", "mailbox.message.sent"],
  "mailboxes": ["mbx_3f9c2a1b7d8e4f6a0b1c2d3e"]
}
```

- The filter only affects mailbox events: every other event the endpoint subscribes to still arrives.
- With a tenant filter too, a mailbox event must pass both.
- `"mailboxes": []` or `null` on `PATCH /webhooks/{id}` removes the filter.
- Webhook objects carry `mailboxes`, as `mbx_` ids, only when filtered.
- Naming a mailbox that does not exist is a `404`.

---

## Delete endpoint

`DELETE /webhooks/{id}`

```json
{ "ok": true }
```

---

## Test sink

`POST /emails/test` (full-scope API key)

```json
{ "event": "email.bounced", "email_id": "msg_…", "deliver": true }
```

Builds a webhook payload (optionally for an existing email) and, when `deliver` is not `false`, enqueues delivery to your subscribed endpoints. Add `"tenant": "cust_8412"` to put that tenant on the payload, so endpoints [filtered to it](#tenant-filters) receive it; testing a filtered endpoint with `webhook_id` needs one of its tenants. Useful in CI. Its payloads carry `"test": true`. For a whole send with every event it produces, use a [simulator address](https://docs.groundmail.dev/testing#simulator-addresses).

---

## Incoming webhook payload

Groundmail `POST`s JSON to your endpoint URL when a subscribed event occurs. Redirects are not followed: a `3xx` is recorded as the response and retried like any other failure, so use the final URL.

### Email event example

```json
{
  "type": "email.received",
  "created_at": "2026-07-25T12:05:00.000Z",
  "data": {
    "email_id": "inb_abc123…",
    "to": ["sales@inbound.example.com"],
    "from": "Sender <sender@example.com>",
    "subject": "Hello",
    "status": "received",
    "rcpt_to": "sales@inbound.example.com",
    "cc": [],
    "message_id": "<abc@example.com>",
    "in_reply_to": null,
    "references": [],
    "in_reply_to_email": null,
    "spam_status": "clean",
    "spam_score": 0.9,
    "attachment_count": 1,
    "attachments": [
      {
        "filename": "invoice.pdf",
        "content_type": "application/pdf",
        "size": 48291
      }
    ],
    "received_at": "2026-07-25T12:04:59.000Z"
  }
}
```

For inbound events, attachment metadata is included but attachment bytes are not — fetch `/received-emails/{id}` for full bodies and base64 attachment data.

When the inbound email is a reply to an email you sent through Groundmail, `in_reply_to_email` is that sent email: `id` (`msg_…`), `subject`, `from`, `to`, `sent_at`, `tags` and `tenant`. It is `null` otherwise. See [Replies to emails you sent](https://docs.groundmail.dev/inbound#replies-to-emails-you-sent).

For bounces, `type` is `email.bounced`, `status` is `bounced`, `bounce_reason` may contain the receiving server's reply, and `bounce_type` says why:

- `hard`: the address cannot receive mail. Groundmail adds it to your suppression list.
- `block`: the receiving server refused the message because of the sending IP's or domain's reputation or policy (for example a blocklist listing). The address is fine and is **not** suppressed, and the bounce does not count toward your bounce rate. Retry later or alert yourself; Groundmail's deliverability team is notified of blocks on its sending IPs.

```json
{
  "type": "email.bounced",
  "created_at": "2026-10-17T15:02:11.000Z",
  "data": {
    "email_id": "msg_abc123…",
    "to": ["user@example.com"],
    "from": "you@yourdomain.com",
    "subject": "Welcome",
    "status": "bounced",
    "bounce_reason": "550 5.7.1 Message rejected due to local policy",
    "bounce_type": "block",
    "tags": [{ "name": "user_id", "value": "u_42" }]
  }
}
```

`bounce_type` is `null` on other events. Treat a value you don't recognize like `hard`.

`data.tags` is the email's `tags` exactly as you sent them (`[]` when it had none), on every outbound `email.*` event. Use a tag carrying your own id (a message or user id) to match an event to your records without first storing Groundmail's `email_id`, for example when an event arrives before your code has saved the send response. `email.received` has no tags of its own; a reply carries the tags of the email it answers in `in_reply_to_email.tags`.

`data.tenant` is the [tenant](https://docs.groundmail.dev/tenants)'s `external_id` on events for a tenant's email, and absent otherwise.

`data.stream` is the mail stream the email went out on: `transactional`, `product` or `newsletter` ([streams](https://docs.groundmail.dev/deliverability#transactional-and-product-streams)). Simulated events and `POST /emails/test` payloads may leave it out.

`data.detected_category` is what Groundmail detected the email is: `transactional`, `product`, or `null` while it's still being checked and for email Groundmail doesn't check ([detected category](https://docs.groundmail.dev/deliverability#detected-category)). It's on every outbound `email.*` event, not on `email.received`.

`data.test` is `true` on simulated events: sends with a test key (`gm_test_…`) or to simulator addresses, and `POST /emails/test`. It is absent on events from real mail. See [Testing](https://docs.groundmail.dev/testing).

### Automation event example

```json
{
  "type": "automation.step_completed",
  "created_at": "2026-07-26T12:05:00.000Z",
  "data": {
    "automation_id": "a1b2c3",
    "automation_name": "Welcome flow",
    "run_id": "r1s2t3",
    "status": "running",
    "event_name": "user.created",
    "step_index": 0,
    "step_type": "send_email",
    "error": null
  }
}
```

### Contact unsubscribe examples

Global unsubscribe (`scope: "all"`) adds the address to suppressions and blocks every send:

```json
{
  "type": "contact.unsubscribed",
  "created_at": "2026-08-02T12:05:00.000Z",
  "data": {
    "email": "user@example.com",
    "source": "unsubscribe",
    "scope": "all",
    "category": null,
    "category_label": null,
    "suppression_id": "sup_…",
    "category_opt_out_id": null,
    "email_id": "msg_…"
  }
}
```

Category opt-out (`scope: "category"`) stops product mail only — transactional messages still send:

```json
{
  "type": "contact.unsubscribed",
  "created_at": "2026-08-02T12:05:00.000Z",
  "data": {
    "email": "user@example.com",
    "source": "unsubscribe",
    "scope": "category",
    "category": "product",
    "category_label": "product emails",
    "suppression_id": null,
    "category_opt_out_id": "opt_…",
    "email_id": "msg_…",
    "tags": [{ "name": "user_id", "value": "u_42" }]
  }
}
```

Check `data.scope` (and `data.category` when scope is `category`) before treating the address as fully suppressed.

When the email carrying the link is known, `data.tags` holds its tags as sent. When it was sent for a [tenant](https://docs.groundmail.dev/tenants), `data.tenant` is that tenant's `external_id`, and the suppression or opt-out applies to that tenant's sends only: your other tenants can still email the address. Unsubscribes from email not sent for a tenant have no `tenant` and apply to the whole account.

---

## Signature verification

Each delivery includes:

```http
Groundmail-Signature: t=1721908800,v1=abc123…
```

### SDK helper (preferred)

```ts
import { Groundmail, verifyWebhookSignature } from 'groundmail'

const ok = verifyWebhookSignature(secret, rawBody, request.headers.get('groundmail-signature'))
// or:
const client = new Groundmail(process.env.GROUNDMAIL_API_KEY!)
client.webhooks.verify(secret, rawBody, header)
```

Verify by:

1. Read the raw request body as a string (before JSON parsing).
2. Parse `t` (Unix timestamp) and `v1` (hex HMAC) from the header.
3. Reject if `t` is more than 5 minutes from your server clock.
4. Compute `HMAC-SHA256(secret, "${t}.${rawBody}")` and compare to `v1` (constant-time).

Return `2xx` quickly from your handler. Your server has 15 seconds to answer each attempt. If your endpoint does not return `2xx`, we retry the delivery 4 more times, after 5 seconds, 30 seconds, 2 minutes and 2 minutes.

---

## Delivery log

Every event sent to an endpoint is logged for 30 days: each attempt with its status code and response time, the payload we sent, and the first 2 KB of what your server replied. In the dashboard, open an endpoint under **Webhooks**, or the **Webhooks** section of an email's detail.

A delivery gets 5 attempts: the first right away, then retries after 5 seconds, 30 seconds, 2 minutes and 2 minutes. Its `status` is one of:

| Status | Meaning |
|--------|---------|
| `pending` | Queued, not attempted yet |
| `retrying` | An attempt failed and another is scheduled (`next_attempt_at`) |
| `delivered` | Your server returned `2xx` |
| `failed` | Every attempt failed |

A test event you send to an endpoint gets one attempt. Simulated events carry `test: true`, so you can filter them with `?test=false`.

### List deliveries

```http
GET /webhooks/{id}/deliveries
```

Newest first, with cursor pagination (`limit`, `cursor`). Filters: `status`, `event`, `email_id`, `test`, and `q` (an exact email id, or part of a recipient address).

```json
{
  "deliveries": [
    {
      "id": "6f1c2a44-8f0e-4c3b-9a55-1d2e3f4a5b6c",
      "webhook_id": "2b7d9f10-3c4e-4a1b-8d6f-0e1f2a3b4c5d",
      "event": "email.delivered",
      "status": "retrying",
      "attempt_count": 2,
      "max_attempts": 5,
      "email_id": "msg_01JC8Q7K2Z",
      "recipient": "leo@example.net",
      "test": false,
      "response_status": 503,
      "error_kind": null,
      "latency_ms": 1180,
      "last_attempt_at": "2026-11-03T14:32:13.000Z",
      "next_attempt_at": "2026-11-03T14:32:44.000Z",
      "resent_from": null,
      "created_at": "2026-11-03T14:32:08.000Z",
      "updated_at": "2026-11-03T14:32:14.000Z"
    }
  ],
  "has_more": false,
  "next_cursor": null
}
```

`error_kind` is `timeout`, `connection` or `blocked_destination` when no response came back; `response_status` is then `null`. `blocked_destination` means the endpoint's URL points to a private or internal address, so no request was made. Update the endpoint to a public URL.

### Retrieve a delivery

```http
GET /webhooks/{id}/deliveries/{deliveryId}
```

The same fields plus `payload` (the event as sent) and `attempts`: each with `attempt`, `started_at`, `response_status`, `error_kind`, `latency_ms`, `response_body` (first 2 KB) and `response_headers` (`content-type`, `content-length`, `retry-after` and `x-request-id` only).

### Resend a delivery

```http
POST /webhooks/{id}/deliveries/{deliveryId}/resend
```

Sends the same payload as a new delivery to the endpoint's current URL, signed afresh, with the usual retries. Returns `202` with the new delivery, which links back through `resent_from`. The original is not changed. The endpoint must be turned on (`409` otherwise), and you can resend 30 deliveries a minute (`429` after that). Use the event's `email_id` or your own ids to ignore a repeat in your handler.

### Endpoint health

`GET /webhooks` and `GET /webhooks/{id}` include `health`:

```json
{
  "last_24h": { "total": 212, "delivered": 175, "failed": 37, "median_latency_ms": 96 },
  "last_delivery_at": "2026-11-03T14:32:13.000Z",
  "last_status": "retrying",
  "last_response_status": 503,
  "failing": true
}
```

`failing` is `true` when at least one delivery failed all 5 attempts in the last 24 hours. `last_24h.failed` counts those deliveries.

---

## SDK

```ts
import { Groundmail } from 'groundmail'

const client = new Groundmail(process.env.GROUNDMAIL_API_KEY!)

const { webhook, secret } = await client.webhooks.create({
  url: 'https://yourapp.com/webhooks/groundmail',
})

const { webhooks } = await client.webhooks.list()
const one = await client.webhooks.get(webhooks[0].id)
await client.webhooks.update(one.webhook.id, { enabled: false })
await client.webhooks.delete(webhooks[0].id)

const { deliveries } = await client.webhooks.deliveries.list(webhooks[0].id, { status: 'failed' })
const { delivery } = await client.webhooks.deliveries.get(webhooks[0].id, deliveries[0].id)
await client.webhooks.deliveries.resend(webhooks[0].id, delivery.id)
```

---

## CLI

```bash
groundmail webhooks list
groundmail webhooks create --url https://yourapp.com/hooks
groundmail webhooks delete --id clx…
groundmail webhooks deliveries list --webhook <webhook-id> --status failed
groundmail webhooks deliveries get --webhook <webhook-id> --id <delivery-id>
groundmail webhooks deliveries resend --webhook <webhook-id> --id <delivery-id>
```

Requires `GROUNDMAIL_API_KEY` or `--api-key`.

---

## OpenAPI

Machine-readable spec: [`openapi/groundmail.yaml`](https://docs.groundmail.dev/openapi.yaml)
