Postilio docs

Webhooks

Postilio posts the events of your messages to an HTTPS endpoint of yours, so you do not have to poll GET /v1/emails/{id}. Deliveries are signed with the Standard Webhooks scheme, so any Standard Webhooks library can verify them, and so can the few lines below.

Endpoints

Add an endpoint on the portal's Webhooks page, or with an API key that has the webhooks:manage scope:

curl https://api.postilio.eu/v1/webhooks \
  -H "Authorization: Bearer $POSTILIO_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://api.example.com/hooks/postilio", "events": ["delivered", "bounced", "complained"] }'

The answer holds the signing secret (whsec_…). It is shown this once; Postilio keeps it encrypted and never returns it again. Rotate it to get a new one.

CallWhat it does
GET /v1/webhooksyour endpoints
POST /v1/webhooksadd one: url (HTTPS), events, optional description, mode (live or test)
GET /v1/webhooks/{id}read one
PATCH /v1/webhooks/{id}change url, events, description or paused; what you leave out stays as it is
DELETE /v1/webhooks/{id}remove it
POST /v1/webhooks/{id}/secretrotate the secret; the old one keeps signing for 24 hours
POST /v1/webhooks/{id}/testsend a webhook.test.v1 event, once (no retries), also to a paused endpoint
GET /v1/webhooks/{id}/deliveriesthe delivery log: attempts, status codes, errors (status, before, limit)
POST /v1/webhooks/{id}/deliveries/{deliveryId}/retryone more attempt right away, same id and payload (resume a paused endpoint first)

Reading (GET on your endpoints and their deliveries) needs webhooks:read or webhooks:manage; everything else needs webhooks:manage. No call returns the secret after the answer that created or rotated it.

A project has at most 10 endpoints, and your organization as many as its plan allows (see Plan limits). A test endpoint only gets the events of messages sent with a pk_test_ key; a live endpoint never does. Test keys cannot manage webhooks.

Moving an endpoint to another project

An Owner or Admin can move an endpoint to another project of the same organization, on its settings page in the portal. Its URL, events, mode and signing secret stay, so your receiver keeps verifying as before. From then on it gets the events of the new project. Deliveries so far stay with the old project, and retries that are still open finish as they were: same webhook-id, same payload, same URL. The move is refused with webhook_endpoint_limit_reached when the new project already has 10 endpoints, and with webhook_url_not_allowed when the URL no longer passes the address check. Moving to another organization is not possible; that is a project transfer.

Which URLs are allowed

Postilio connects only to public addresses, so a webhook cannot be used to reach anything on Postilio's own network:

Try it: the test event

Send a test event to see that your endpoint is reachable and verifies the signature:

curl -X POST https://api.postilio.eu/v1/webhooks/$WEBHOOK_ID/test \
  -H "Authorization: Bearer $POSTILIO_KEY"

It answers 202 with the delivery, which is tried once right away, also when the endpoint is paused. Look at the result in the delivery log, with the status code your endpoint answered and the start of its body:

curl "https://api.postilio.eu/v1/webhooks/$WEBHOOK_ID/deliveries?limit=5" \
  -H "Authorization: Bearer $POSTILIO_KEY"

Events and payload

EventWhen
acceptedthe API or SMTP took the message
queuedhanded to the mail server
deliveredthe receiving server accepted it
deferreda temporary failure; it is retried
bouncedrefused for good (also a bounce that arrives later)
expirednot delivered within a day
complainedthe recipient marked it as spam
suppressednot sent: the address is on the suppression list
scheduledthe message waits for its sendAt (Scheduled sending); data.sendAt says when
canceleda scheduled message will not be sent: canceled, or no longer allowed when it was due; data.reason says why
inbounda message arrived at one of your inbound routes: inbound.received.v1, see Inbound mail

An endpoint gets only the events it chose: one made before scheduled and canceled existed does not get them until you add them to its events.

The body is JSON. type carries the version: a change that is not backwards compatible gets a new type (email.delivered.v2) instead of changing this one. Fields without a value are left out, and new fields may be added. Email events never carry message content: no subject, no body. The inbound event does, because that is what it is for. reason, response and the codes mean the same as in a message's timeline: see Delivery status and reasons. A scheduled message's events also carry sendAt. A bounce that arrived after delivery carries "async": true and "reason": "async_bounce" (A bounce after delivery); its email.bounced.v1 can follow an email.delivered.v1 for the same emailId, hours or days later. A complaint carries "async": true and "reason": "feedback_loop" (A complaint after delivery).

{
  "type": "email.bounced.v1",
  "timestamp": "2026-10-03T14:07:45.102+00:00",
  "data": {
    "emailId": "0199a7c4-5a1e-7d2b-9c41-6f3e0b8a2d17",
    "projectId": "0199a1b2-0000-7000-8000-000000000001",
    "to": "ada.lovelace@example.com",
    "tag": "sign-in",
    "test": false,
    "event": "bounced",
    "occurredAt": "2026-10-03T14:07:45.102+00:00",
    "attempt": 1,
    "smtpCode": 550,
    "enhancedCode": "5.1.1",
    "classification": "InvalidRecipient",
    "reason": "recipient_rejected",
    "response": "550 5.1.1 The email account that you tried to reach does not exist",
    "remoteHost": "mx.example.com"
  }
}

webhook.test.v1 has data.endpointId, data.projectId and data.test only.

Inbound mail: inbound.received.v1

Inbound mail is in an invite-only preview. A message that arrives at an address of one of your receiving domains is taken only when an inbound route matches the address: an exact address (support), else the longest prefix (reply+ matches reply+4821@…), else the domain's catch-all, which is off until you make one. Any other address is refused while the sender is still connected (550 5.1.1), and a paused route asks the sender to try later (450 4.2.1): Postilio never sends a bounce of its own afterwards. A route delivers to one endpoint of its project, in the same mode (a test route to a test endpoint), that has inbound among its events; the event is not in a new endpoint's default selection; a route made through the API turns it on. Mail is always real; the mode only separates the streams. Set up receiving domains and routes, and fetch or redeliver received messages, as in Inbound mail.

Each route can hold mail back after the message is read: senders it does not allow (senderAllow: addresses or @domain, matched on the From header), mail that fails DMARC (requireDmarc), and mail rspamd would reject (spamAction: "filter_reject", the default; "deliver_all" sends everything with its score). Held-back mail gets no webhook and does not count in your monthly volume.

{
  "type": "inbound.received.v1",
  "timestamp": "2026-10-21T13:52:50.102+00:00",
  "data": {
    "inboundId": "01a1527c-8e14-7b2a-9c51-3f0e2d6a4b10",
    "projectId": "0199a1b2-0000-7000-8000-000000000001",
    "routeId": "01a15270-3c4d-7e5f-8a6b-7c8d9e0f1a2b",
    "test": false,
    "receivedAt": "2026-10-21T13:52:48.611+00:00",
    "envelope": { "mailFrom": "marie@example.org", "recipients": ["support@inbound.northwind-labs.eu"],
                  "remoteIp": "209.85.220.41", "helo": "mail-sor-f41.google.com", "tls": "TLSv1.3" },
    "from": { "name": "Marie Curie", "address": "marie@example.org" },
    "to": [{ "name": "Northwind support", "address": "support@inbound.northwind-labs.eu" }],
    "cc": [],
    "replyTo": [],
    "subject": "Re: Your order 4821",
    "date": "2026-10-21T15:52:41+02:00",
    "messageId": "<CAF4x9@mail.gmail.com>",
    "inReplyTo": "<01a14f7e2b6d7c119a3e5d0c8e1f4a27@northwind-labs.eu>",
    "references": ["<01a14f7e2b6d7c119a3e5d0c8e1f4a27@northwind-labs.eu>"],
    "related": { "emailId": "01a14f7e-2b6d-7c11-9a3e-5d0c8e1f4a27", "match": "in_reply_to" },
    "text": "Hi, the parcel arrived damaged…",
    "textTruncated": false,
    "textFromHtml": false,
    "html": "<div dir=\"ltr\">Hi, the parcel arrived damaged…</div>",
    "htmlTruncated": false,
    "headers": [{ "name": "Received", "value": "from mail-sor-f41.google.com …" }],
    "attachments": [{ "index": 0, "filename": "photo.jpg", "contentType": "image/jpeg", "size": 482113,
                      "sha256": "9f2c…", "disposition": "attachment", "contentId": null, "risk": "none",
                      "url": "https://api.postilio.eu/v1/inbound/messages/01a1527c-8e14-7b2a-9c51-3f0e2d6a4b10/attachments/0" }],
    "auth": { "spf": { "result": "pass", "domain": "example.org" },
              "dkim": [{ "result": "pass", "domain": "example.org", "selector": "s1", "aligned": true }],
              "dmarc": { "result": "pass", "policy": "none", "aligned": true },
              "arc": null },
    "spam": { "score": 1.2, "verdict": "clean", "symbols": ["MIME_GOOD"] },
    "parseError": null,
    "parseWarnings": [],
    "contentExpiresAt": "2026-10-25T13:52:48.611+00:00"
  }
}

Inbound mail is untrusted input. Anyone can write to an address that takes mail, and the html is exactly what a browser would run, also after a character set like UTF-7 is decoded. Never show the html without sanitizing it. If an AI model reads inbound mail, give it text only, mark it as data from a stranger, never let it act on instructions in it without a person confirming, and check auth first.

Delivery

Verifying the signature

Every request has three headers:

HeaderContent
webhook-idthe event id: drop repeats by it
webhook-timestampwhen it was sent, in Unix seconds
webhook-signaturev1, and the base64 of HMAC-SHA256 over {webhook-id}.{webhook-timestamp}.{body}, keyed with the base64-decoded part of the secret after whsec_

During the 24 hours after a rotation the header holds two signatures separated by a space, one per secret; accept the request when either matches. Refuse a timestamp more than five minutes off, so a captured request cannot be replayed later. Verify the raw body, before parsing it: re-serialized JSON is not byte for byte the same.

Seal's notification channels to your own endpoint are signed the same way (Seal).

These examples need no packages. Postilio's own tests run them against the Standard Webhooks test vector.

Node

// Verifies a Postilio webhook (the Standard Webhooks scheme) with Node's own crypto; no packages needed.
import { createHmac, timingSafeEqual } from 'node:crypto';

const TOLERANCE_SECONDS = 5 * 60;

/**
 * True when one of the signatures matches and the timestamp is less than five minutes off.
 * `body` is the raw request body as a string: verify before parsing it.
 */
export function verifyWebhook(secret, { id, timestamp, signature }, body, nowSeconds = Math.floor(Date.now() / 1000)) {
  const sent = Number(timestamp);
  if (!Number.isInteger(sent) || Math.abs(nowSeconds - sent) > TOLERANCE_SECONDS) {
    return false;
  }
  const key = Buffer.from(secret.startsWith('whsec_') ? secret.slice(6) : secret, 'base64');
  const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${body}`).digest();
  // During a secret rotation the header holds two signatures, space-separated.
  return signature.split(' ').some((part) => {
    const [version, value] = part.split(',', 2);
    const given = Buffer.from(value ?? '', 'base64');
    return version === 'v1' && given.length === expected.length && timingSafeEqual(given, expected);
  });
}

// Usage: node verify.mjs <secret> <webhook-id> <webhook-timestamp> <webhook-signature> <body> [now]
if (import.meta.url === `file://${process.argv[1]}`) {
  const [secret, id, timestamp, signature, body, now] = process.argv.slice(2);
  const ok = verifyWebhook(secret, { id, timestamp, signature }, body, now ? Number(now) : undefined);
  console.log(ok ? 'valid' : 'invalid');
  process.exit(ok ? 0 : 1);
}

Python

"""Verifies a Postilio webhook (the Standard Webhooks scheme) with the standard library; no packages needed."""
import base64
import hashlib
import hmac
import sys
import time

TOLERANCE_SECONDS = 5 * 60


def verify_webhook(secret: str, msg_id: str, timestamp: str, signature: str, body: str, now: int | None = None) -> bool:
    """True when one of the signatures matches and the timestamp is less than five minutes off.

    `body` is the raw request body: verify before parsing it.
    """
    now = int(time.time()) if now is None else now
    if not timestamp.isdigit() or abs(now - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(key, f"{msg_id}.{timestamp}.{body}".encode(), hashlib.sha256).digest()
    # During a secret rotation the header holds two signatures, space-separated.
    for part in signature.split():
        version, _, value = part.partition(",")
        try:
            given = base64.b64decode(value, validate=True)
        except ValueError:
            continue
        if version == "v1" and hmac.compare_digest(given, expected):
            return True
    return False


# Usage: python3 verify.py <secret> <webhook-id> <webhook-timestamp> <webhook-signature> <body> [now]
if __name__ == "__main__":
    secret, msg_id, timestamp, signature, body, *rest = sys.argv[1:]
    ok = verify_webhook(secret, msg_id, timestamp, signature, body, int(rest[0]) if rest else None)
    print("valid" if ok else "invalid")
    sys.exit(0 if ok else 1)

C#

using System.Security.Cryptography;
using System.Text;

namespace Postilio.Webhooks;

/// <summary>
/// Verifies a Postilio webhook (the Standard Webhooks scheme). Copy it into your project; it needs no packages.
/// </summary>
public static class WebhookVerifier
{
    private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5);

    /// <summary>
    /// True when one of the signatures in <paramref name="signatureHeader"/> matches and the timestamp is less than
    /// five minutes off, which turns away a replayed request. Pass the raw body, not a re-serialized one.
    /// </summary>
    public static bool Verify(string secret, string id, string timestamp, string signatureHeader, string body, DateTimeOffset now)
    {
        if (!long.TryParse(timestamp, out var seconds) || (now - DateTimeOffset.FromUnixTimeSeconds(seconds)).Duration() > Tolerance)
        {
            return false;
        }
        var key = Convert.FromBase64String(secret.StartsWith("whsec_", StringComparison.Ordinal) ? secret[6..] : secret);
        var expected = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes($"{id}.{timestamp}.{body}"));
        // During a secret rotation the header holds two signatures, space-separated: "v1,<a> v1,<b>".
        foreach (var signature in signatureHeader.Split(' ', StringSplitOptions.RemoveEmptyEntries))
        {
            var parts = signature.Split(',', 2);
            var given = new byte[expected.Length];
            if (parts is ["v1", var value] && Convert.TryFromBase64String(value, given, out var length) && length == given.Length
                && CryptographicOperations.FixedTimeEquals(given, expected))
            {
                return true;
            }
        }
        return false;
    }
}

For example in ASP.NET Core:

app.MapPost("/hooks/postilio", async (HttpRequest request) =>
{
    using var reader = new StreamReader(request.Body);
    var body = await reader.ReadToEndAsync();
    var h = request.Headers;
    if (!WebhookVerifier.Verify(secret, h["webhook-id"].ToString(), h["webhook-timestamp"].ToString(), h["webhook-signature"].ToString(), body, DateTimeOffset.UtcNow))
    {
        return Results.Unauthorized();
    }
    // Queue the work, drop it when webhook-id was seen before, and answer at once.
    return Results.NoContent();
});