# Webhooks

A webhook is an HTTPS endpoint you own. mailbot POSTs a signed JSON body to it when something happens to an email in your account. This page describes what the server does today, read from the code, not what is planned.

## Register an endpoint

```bash
curl -X POST https://getmail.bot/v1/webhooks \
  -H "Authorization: Bearer $MAILBOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/mailbot",
    "events": ["message.sent", "message.received"]
  }'
```

The response includes the webhook `id` and its `secret`. Store the secret; you need it to verify signatures. The URL must be public HTTPS. Private and link-local addresses are rejected, and a redirect is followed at most once and re-validated.

## Events that reach your webhook

| Event | When it fires | Where it is produced |
|---|---|---|
| `message.sent` | An outbound message was accepted by the API and handed to the sender (also for scheduled sends when they go out) | send, reply, scheduled send |
| `message.received` | An inbound email arrived in one of your inboxes | inbound parser |
| `message.delivered` | The recipient server accepted the message, without proving inbox placement | authenticated provider callback |
| `message.opened` | An open was reported; tracking can be affected by privacy tools | authenticated provider callback |
| `message.clicked` | A tracked link click was reported | authenticated provider callback |
| `message.bounced` | A bounce was reported | authenticated provider callback |
| `message.complained` | A complaint was reported | authenticated provider callback |

All seven event types use a durable outbox before queue dispatch. Engagement events are committed with authenticated callback receipts and are also published on the realtime stream. A repeated callback receipt cannot create a second event. Callback ingress must be explicitly enabled with verified provider signing; if it is disabled or unconfigured, subscribing does not create missing events. Read current message state with `GET /v1/inboxes/{inbox_id}/messages/{id}` or `get_message`.

## Request your endpoint receives

Headers:

```
Content-Type: application/json
X-Mailbot-Event: message.received
X-Mailbot-Signature: <hex HMAC-SHA256 of the raw body>
```

Every plan also receives:

```
X-Mailbot-Event-Id: <uuid>
X-Mailbot-Delivery-Attempt: 1
Idempotency-Key: <same uuid>
```

Body:

```json
{
  "event": "message.received",
  "event_id": "b3f0d0a2-1c8e-4a7e-9d2b-7c1f5f0a9e11",
  "delivery_attempt": 1,
  "timestamp": "2026-10-19T03:15:06.262Z",
  "data": {
    "id": "msg-uuid",
    "inbox_id": "inbox-uuid",
    "thread_id": "thread-uuid",
    "from_address": "customer@example.com",
    "to_addresses": ["support@yourdomain.com"],
    "cc_addresses": [],
    "bcc_addresses": [],
    "subject": "Re: Your support request",
    "direction": "inbound",
    "received_at": "2026-10-19T03:15:05.000Z",
    "duplicate": false
  }
}
```

`message.sent` carries the same shape with `direction: "outbound"`, plus `compliance_status`, `delivery_status`, and `scheduled_at` when the send was scheduled. Fetch the full message by `data.id` if you need the body.

Delivery/engagement event `data` contains `inbox_id`, `thread_id`, `message_id`,
`transmission_id` (nullable), `recipient`, `status`, `timestamp` (ISO 8601), and
nullable `bounce_type`, `bounce_code`, `bounce_reason`. The envelope and HMAC
scheme are the same. These events use `data.message_id`, not `data.id`.

## Verify the signature

The signature is HMAC-SHA256 over the **raw request body bytes**, hex encoded, using the webhook secret. There is no timestamp in the signature and no `sha256=` prefix. Compare with a constant-time function.

Node.js (Express, raw body):

```javascript
const crypto = require('crypto');
const express = require('express');

const app = express();
app.post('/webhooks/mailbot', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = crypto.createHmac('sha256', process.env.MAILBOT_WEBHOOK_SECRET).update(req.body).digest('hex');
  const given = req.get('X-Mailbot-Signature') || '';
  const ok = expected.length === given.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(given));
  if (!ok) return res.status(401).send('bad signature');

  const event = JSON.parse(req.body.toString('utf8'));
  // event.event, event.event_id, event.data
  res.sendStatus(200);
});
```

Python (Flask):

```python
import hashlib, hmac, os
from flask import Flask, request

app = Flask(__name__)

@app.post("/webhooks/mailbot")
def mailbot_webhook():
    expected = hmac.new(os.environ["MAILBOT_WEBHOOK_SECRET"].encode(), request.get_data(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Mailbot-Signature", "")):
        return "bad signature", 401
    event = request.get_json()
    # event["event"], event["event_id"], event["data"]
    return "ok", 200
```

## Timeouts and retries

Your endpoint has 30 seconds to answer. Any 2xx counts as delivered.

| Behavior | Every plan |
|---|---|
| Attempts | 7 total |
| Delay between attempts | 1s, 2s, 4s, 8s, 16s, 32s |
| Failed deliveries kept for replay (dead-letter queue) | Yes |
| Signed replay from the API | Yes |
| `X-Mailbot-Event-Id` and `Idempotency-Key` headers | Yes |

Older jobs keep the retry options with which they were queued. Delivery is at
least once, so deduplicate by event ID. Use `GET /v1/webhooks/{id}/deliveries` to
see each attempt with its status code and duration. Exhausted retries do not
guarantee delivery. Current webhook destinations and secrets are checked at
dispatch; SSRF and tenant checks still apply during replay.

## Good practice

- Verify the signature and persist the event durably before answering 200. Process slower work in a queue within your application.
- Treat `event_id` as the idempotency key for your side. With retries on, the same `event_id` can arrive more than once.
- Verify every request before parsing it.
- Keep the subscription list to what you handle. Unsubscribed events are not sent.
