Webhooks

Register an HTTPS endpoint and Trotta Mail posts an event to it the moment something happens. Every request is signed.

#Create a webhook

shell
curl -X POST https://api.trotta.email/v1/webhooks \
  -H "Authorization: Bearer $TROTTA_MAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/hooks/trotta-mail", "event_types": ["message.received", "message.held"]}'

The response includes a secret that starts with whsec_. Store it now: it is not shown again. Lost it? POST /v1/webhooks/{id}/rotate-secret returns a new one, and the old one stops signing at once.

Leave out event_types and you get message.received only. Add inbox_id to hear about one inbox. The key needs the admin scope.

In production the URL must be https and resolve only to public addresses, or the call answers 400 unsafe_url. Redirects are never followed.

#Events

TypeWhen
message.receivedAn inbound message was delivered, or a held one was released.
message.heldAn inbound message was held for a human. The message is withheld.
message.rejectedAn inbound message was refused at SMTP time.
message.releasedA human released a held message.
message.sentAn outbound message left.
message.deliveredThe receiving server accepted it.
message.bouncedThe receiving server refused it.
message.blockedThe outbound screen stopped a message.
message.pending_approvalAn outbound message is waiting for a human.
message.scheduledA message was scheduled to go later.
message.schedule_failedA scheduled message was refused when due. It is a draft again.
inbox.createdAn inbox was created.
domain.verifiedA custom domain passed its DNS checks.

The body of every request is an Event:

POST to your endpoint
{
  "id": "evt_1Vb6kRs3",
  "type": "message.received",
  "created_at": "2026-11-18T10:00:00Z",
  "organization_id": "org_5mTz81Qd",
  "inbox_id": "inb_7Qh2mXc4",
  "data": {
    "message": { "id": "msg_8Kd2pXw1", "subject": "Your Harbor verification code", "text": "..." },
    "thread": { "id": "thr_2bN8pLw1", "message_count": 1 }
  }
}

The message inside an event is the safe view, so you can pass it on without a second fetch. For held mail it is withheld: where it is and why, and nothing the sender wrote.

#Verify the signature

Requests follow the Standard Webhooks scheme. Three headers arrive with each one: webhook-id, webhook-timestamp (unix seconds) and webhook-signature (v1,<base64>). The signature is HMAC-SHA256 over {id}.{timestamp}.{body}, keyed with the base64 part of your whsec_ secret. Verify against the raw request body, before any JSON parsing.

#With the TypeScript SDK

typescript
import { TrottaMail } from "trotta-mail";

const mail = new TrottaMail({ apiKey: process.env.TROTTA_MAIL_API_KEY });

// Express: use express.raw({ type: "application/json" }) on this route.
app.post("/hooks/trotta-mail", async (req, res) => {
  let event;
  try {
    event = await mail.webhooks.verify(req.body.toString(), req.headers, process.env.TROTTA_MAIL_WEBHOOK_SECRET);
  } catch {
    return res.status(400).send("Bad signature");
  }
  if (event.type === "message.received") {
    // event.data.message is the safe view.
  }
  res.sendStatus(200);
});

#With the Python SDK

python
import os

from trottamail import verify_webhook

# Flask: request.get_data() is the raw body, exactly as it was signed.
@app.post("/hooks/trotta-mail")
def hook():
    try:
        event = verify_webhook(request.get_data(), request.headers, os.environ["TROTTA_MAIL_WEBHOOK_SECRET"])
    except ValueError:
        return "Bad signature", 400
    if event["type"] == "message.received":
        pass  # event["data"]["message"] is the safe view.
    return "", 200

#By hand, in TypeScript

typescript
import { createHmac, timingSafeEqual } from "node:crypto";

export function verify(rawBody: string, headers: Record<string, string>, secret: string) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const given = headers["webhook-signature"] ?? "";

  // Refuse anything older than five minutes.
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error("Stale webhook");

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  // An unset secret would make an empty key, and anyone can sign with an empty key.
  if (key.length < 16) throw new Error("No webhook secret");
  const expected = createHmac("sha256", key).update(id + "." + timestamp + "." + rawBody).digest("base64");

  const ok = given.split(" ").some((part) => {
    const [version, signature] = part.split(",");
    if (version !== "v1" || !signature) return false;
    const a = Buffer.from(signature);
    const b = Buffer.from(expected);
    return a.length === b.length && timingSafeEqual(a, b);
  });
  if (!ok) throw new Error("Bad signature");
  return JSON.parse(rawBody);
}

#By hand, in Python

python
import base64, hashlib, hmac, json, time


def verify(raw_body: bytes, headers: dict, secret: str) -> dict:
    msg_id = headers["webhook-id"]
    timestamp = headers["webhook-timestamp"]

    # Refuse anything older than five minutes.
    if abs(time.time() - int(timestamp)) > 300:
        raise ValueError("Stale webhook")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    # An unset secret would make an empty key, and anyone can sign with an empty key.
    if len(key) < 16:
        raise ValueError("No webhook secret")
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    for part in headers.get("webhook-signature", "").split(" "):
        version, _, signature = part.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return json.loads(raw_body)
    raise ValueError("Bad signature")

#Retries

Answer with any 2xx status to acknowledge. Anything else, or no answer, is retried after 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours and 8 hours. The webhook-id stays the same across retries, so use it to ignore duplicates.

Delivery is separate for every organization: a slow endpoint holds up its own deliveries and nobody else's. Up to 2,000 can be queued. Past that, events stay in the log: catch up with GET /v1/events.

#Test and replay

POST /v1/webhooks/{id}/test sends a signed sample message.received. GET /v1/webhooks/{id}/deliveries shows what was sent and how your endpoint answered, and POST /v1/webhooks/deliveries/{id}/replay sends one again.