# Webhooks

> The Call a web address rule step, the exact HTTP request and JSON payload it sends, retries and delivery guarantees, address restrictions, and how to receive it safely.

Source: https://docs.posternmail.app/rules/webhooks/

The **Call a web address** step tells another service that a matching message arrived, for
example a home automation system, a ticket tool or your own script. This page describes the
request the Hub sends, the payload, retries, and how to build a receiver.

## Set it up

1. Open the rule in **Settings → Rules** and choose **Add a step** → **Call a web address**.
2. In **Web address**, type the URL of your receiver, for example
   `https://hooks.example.com/postern`. It must start with `http://` or `https://` and be at
   most 2,000 characters.
3. Save the rule. Rules with a webhook do not start in Test mode by themselves; pick **Test**
   first if you want to see what would be sent.

> **Check:** when the next matching message arrives, **Settings → Rule activity** shows "Call
> webhook hooks.example.com" with **Done** and the detail "Delivered (HTTP 200)" (or the status
> your receiver returned).

> **If it did not work:** the entry shows **Failed** with "Webhook failed: ..." and the reason,
> and you get the alert "A rule's webhook could not be delivered to hooks.example.com: ...".
> While the Hub is still retrying, the entry shows **Done** with "Queued (rjb_...)": the call is
> handed to the background worker and not finished yet.

You can add the step several times to call several addresses. Webhooks run only on the Hub.

## The request

```http
POST /postern HTTP/1.1
Host: hooks.example.com
Content-Type: application/json
User-Agent: Postern/dev
X-Postern-Event: rule.matched
X-Postern-Delivery: rjb_7q2m4xk6d3h5p5a2c6v7b2n4zt

{"event":"rule.matched", ...}
```

| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `User-Agent` | `Postern/<version>`. A Hub built from source says `Postern/dev`. |
| `X-Postern-Event` | Always `rule.matched` |
| `X-Postern-Delivery` | The delivery ID, the same as `deliveryId` in the body |

There is no signature header. The Hub does not sign webhook requests. See
[Receive webhooks safely](https://docs.posternmail.app/rules/webhooks/#receive-webhooks-safely).

## Payload reference

| Field | Type | Always there | Meaning |
|---|---|---|---|
| `event` | string | yes | Always `"rule.matched"` |
| `deliveryId` | string | yes | `rjb_` followed by 26 lowercase letters and digits. The same for every retry of this delivery, and for this rule, message and step. Use it to drop duplicates. |
| `ruleId` | string | yes | The rule's ID, `rul_...` |
| `rule` | string | yes | The rule's name at the time of the match |
| `mailboxId` | string | yes | The mailbox's ID, `mbx_...` |
| `mailbox` | string | yes | The mailbox's email address |
| `sender` | string | yes | The sender's email address (From) |
| `senderName` | string | no | The sender's display name, if the message has one |
| `subject` | string | yes | The subject, empty string if there is none |
| `messageIdHeader` | string | no | The message's `Message-ID` header, without `<` and `>` |
| `receivedAt` | string | no | When the message arrived, UTC, in the form `2026-12-05T09:14:03.000Z`. Falls back to the message's `Date` if the provider gave no receive time. |

The message text, attachments and the other recipients are never sent. The editor says so under
the field: "Gets the rule name, mailbox, sender and subject. Never the message text."

### Full example

```json
{
  "event": "rule.matched",
  "deliveryId": "rjb_7q2m4xk6d3h5p5a2c6v7b2n4zt",
  "ruleId": "rul_01jf8k2m3n4p5q6r7s8t9v0w1x",
  "rule": "Invoices from Acme",
  "mailboxId": "mbx_01jf7a2b3c4d5e6f7g8h9j0k1m",
  "mailbox": "you@example.com",
  "sender": "billing@acme.com",
  "senderName": "Acme Billing",
  "subject": "Invoice 1042 for December",
  "messageIdHeader": "20261205091403.4f2a@mail.acme.com",
  "receivedAt": "2026-12-05T09:14:03.000Z"
}
```

The ID values above are made up for the example.

## Responses, timeouts and retries

| Your receiver answers | The Hub |
|---|---|
| Any `2xx` status | Records **Done** with "Delivered (HTTP 200)" (with your status) |
| `408` or `429` | Retries |
| Any other `4xx` | Gives up at once: **Failed** and an alert |
| `5xx`, no answer, connection refused, timeout | Retries |

- Each request may take up to 10 seconds, then it counts as a timeout. Answer quickly and do
  slow work after you have responded.
- Retries come after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours. After the last one,
  the activity entry becomes **Failed** with "Webhook failed: ..." and the alert "A rule's
  webhook could not be delivered to ..." is raised.
- The response body is ignored.
- Up to 3 redirects are followed, each one checked like the original address. Note that a `301`,
  `302` or `303` redirect turns the `POST` into a `GET` without a body, so point the step at the
  final address.
- The Hub does not use an HTTP proxy for webhooks.

**Delivery is at least once.** The Hub records the delivery before it sends it, and resends it
after a restart if it does not know the result. Your receiver may therefore see the same
`deliveryId` twice. It will not see a delivery zero times unless all retries fail, in which case
you get an alert.

Calls are made one message at a time, in the background. A slow receiver does not hold up your
mail or other rules.

## Which addresses are allowed

To protect your network, the Hub only calls public internet addresses. It checks the address
after it has looked up the host name, on every connection, so a name that later points
elsewhere is caught too.

Always refused:

- `localhost`, names ending in `.localhost`, loopback (`127.0.0.0/8`, `::1`),
- link-local addresses (`169.254.0.0/16`, `fe80::/10`), which include cloud metadata services,
- addresses with a user name or password in them (`https://user:pass@...`),
- other reserved and documentation ranges (`0.0.0.0/8`, `192.0.2.0/24`, `198.18.0.0/15`,
  multicast and others).

Refused unless your admin set `POSTERN_RULES_ALLOW_LAN=1`:

- private networks: `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `100.64.0.0/10`
  (Tailscale and carrier NAT), `fc00::/7`,
- names ending in `.local`, `.internal`, `.lan` and `.home.arpa`, and names without a dot (such
  as `homeassistant`).

How to set the variable for each install method is described under
[Servers in your own network](https://docs.posternmail.app/rules/alerts/#servers-in-your-own-network) on the Alerts page.

> [!NOTE]
> A Home Assistant or Node-RED on your LAN, such as `http://192.168.1.20:8123/api/webhook/...`,
> needs `POSTERN_RULES_ALLOW_LAN=1`.

## Receive webhooks safely

Because requests are not signed, anyone who knows your receiver's address can send it a fake
`rule.matched` request. Protect it like this:

- **Put a secret in the address.** Use a long random path or query parameter, for example
  `https://hooks.example.com/postern/3f9c1a7e5b2d4c8f`, and reject everything else. Use `https`
  so the secret is not readable on the way.
- **Treat the payload as untrusted.** `sender`, `senderName` and `subject` come from whoever sent
  the mail. Never run them as commands or insert them into HTML or SQL unescaped.
- **Drop duplicates** by `deliveryId`.
- **Answer fast** with `200` or `204`, then do the work.

### Example receiver

A small receiver in Python (3.9 or later, standard library only) that checks the secret path,
drops duplicates and logs the message:

```python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET_PATH = "/postern/3f9c1a7e5b2d4c8f"
seen = set()  # use a database in real use; this is lost on restart

class Hook(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != SECRET_PATH:
            self.send_response(404)
            self.end_headers()
            return
        length = int(self.headers.get("Content-Length", 0))
        body = json.loads(self.rfile.read(length) or b"{}")
        delivery = self.headers.get("X-Postern-Delivery") or body.get("deliveryId")
        self.send_response(204)
        self.end_headers()
        if body.get("event") != "rule.matched" or delivery in seen:
            return
        seen.add(delivery)
        print(f"{body['rule']}: {body.get('senderName') or body['sender']} wrote {body['subject']!r}")

HTTPServer(("0.0.0.0", 8000), Hook).serve_forever()
```

Run it behind a reverse proxy with HTTPS, and set the step's **Web address** to
`https://hooks.example.com/postern/3f9c1a7e5b2d4c8f`.

### Test your receiver by hand

Send the example payload yourself:

```sh
curl -i -X POST https://hooks.example.com/postern/3f9c1a7e5b2d4c8f \
  -H 'Content-Type: application/json' \
  -H 'X-Postern-Event: rule.matched' \
  -H 'X-Postern-Delivery: rjb_test0000000000000000000000' \
  -d '{"event":"rule.matched","deliveryId":"rjb_test0000000000000000000000","ruleId":"rul_test","rule":"Test","mailboxId":"mbx_test","mailbox":"you@example.com","sender":"billing@acme.com","subject":"Hello"}'
```

A `204` or `200` in the first line of the output means your receiver accepted it.
