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.
| Call | What it does |
|---|---|
GET /v1/webhooks | your endpoints |
POST /v1/webhooks | add 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}/secret | rotate the secret; the old one keeps signing for 24 hours |
POST /v1/webhooks/{id}/test | send a webhook.test.v1 event, once (no retries), also to a paused endpoint |
GET /v1/webhooks/{id}/deliveries | the delivery log: attempts, status codes, errors (status, before, limit) |
POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry | one 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:
https://only, at most 2048 characters, without credentials (user:pass@) or a#fragment. Authenticate deliveries by their signature; a token in the query string is fine.- No private, loopback, link-local (cloud metadata), shared, documentation, multicast or reserved addresses, for IPv4 and IPv6 alike. A host name without a dot, or ending in
.localhostor.internal, is refused when you add it. - The check runs again on every delivery, against the addresses the host name resolves to at that moment, and the connection goes to the address that was checked. A name that later points somewhere private gets its deliveries refused, and they count as failed.
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
| Event | When |
|---|---|
accepted | the API or SMTP took the message |
queued | handed to the mail server |
delivered | the receiving server accepted it |
deferred | a temporary failure; it is retried |
bounced | refused for good (also a bounce that arrives later) |
expired | not delivered within a day |
complained | the recipient marked it as spam |
suppressed | not sent: the address is on the suppression list |
scheduled | the message waits for its sendAt (Scheduled sending); data.sendAt says when |
canceled | a scheduled message will not be sent: canceled, or no longer allowed when it was due; data.reason says why |
inbound | a 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"
}
}
- Fields are always there, also when empty (
null,[]), unlike the email events. webhook-idis theinboundId: every attempt, retry and replay of the message has it.- Content:
textandhtmlare each cut at 256 KiB (textTruncated,htmlTruncated); the whole body stays under 1 MiB.textFromHtmlsays the text was taken from the html because there was no plain part. Attachments are never in the body, only their metadata;urlfetches one with an API key.riskisexecutable,macro,archiveornone, from the file name and its first bytes; nothing is scanned for viruses. headersare every header in order, decoded;subject,fromand the rest are read from them.relatednames an email your project sent when this message replies to it: byIn-Reply-To("match": "in_reply_to"), else by the last ofReferences("references");nullotherwise. Headers can be made up, so treat it as a hint, not proof.authis what Postilio's checks found: SPF of the envelope sender, every DKIM signature (aligned: it passed for theFromdomain or a parent or child of it), DMARC of theFromdomain, and ARC when the message has a seal. Results arepass,fail,softfail,neutral,none,temperrororpermerror. Trustfromonly withauth.dmarc.resultpass. An ARCpassdoes not turn a DMARCfailinto a pass.spam.verdictisclean,suspect(rspamd would mark it) orspam(rspamd would reject it), with the score and up to ten of the rules that weighed most;unscoredwhen the check did not answer: the message is never held up for it.parseErroris set when the message could not be read within the limits: a header section over 256 KiB or one header over 16 KiB (headers_too_large), more than 100 MIME parts (too_many_parts), no readable message (unreadable), reading took over 10 seconds (parse_timeout), or reading failed three times (parse_failed). Then only the envelope and what could be read are there.parseWarningshascharset_unknownfor text in a character set nobody knows, read as Latin-1.contentExpiresAt: the content is kept 24 hours after the message was delivered, and 4 days after it arrived at the latest. A delivery whose content went before its turn fails withcontent_expired, and nothing is sent. Until thenGET /v1/inbound/messages/{id}has the same data,…/rawthe whole message andPOST …/redeliversends the event again; afterwards they answer410withinbound_content_deleted(Inbound mail).
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
- At least once, in no particular order. The same event can arrive twice (a retry after an answer that got lost), and the events of one email can arrive out of order: a
deliveredcan arrive before itsqueued. A delivery that fails waits for its retry while the endpoint's newer events go ahead, so after a failedaccepteditsdeliveredcan arrive first. That is on purpose: one event your endpoint keeps refusing never holds up the others. Every event has onewebhook-id, the same in every attempt, retry and replay: store the ids you handled and drop repeats. To keep the latest status of an email, comparedata.occurredAtand ignore an event older than the one you already have. - Success is any 2xx answer within 10 seconds. Answer first, then do the work. Redirects are not followed and count as a failure; register the final URL. Postilio reads at most the first kilobyte of your answer.
- One request at a time per endpoint. Endpoints are served in turn, a few seconds each, so a slow endpoint mostly slows its own deliveries; many slow endpoints at once delay the others too.
- Retries after a failure: 30 seconds, then doubling each time (1, 2, 4 … minutes) up to 6 hours between attempts, with some random spread, for 3 days after the event. That is about 20 attempts; a delivery that has not succeeded by then is
failedafter its next attempt. After a failure the endpoint also rests for 30 seconds before its next delivery. - Paused after 3 days of failures. When every attempt to an endpoint failed for 3 days, Postilio pauses it and mails the organization's owners. A paused endpoint gets no new events (they stay in the message log); resume it on the dashboard or with
PATCH {"paused": false}, and retry failed deliveries from the log. - Replaying deliveries. In the portal, each delivery in an endpoint's log has Retry now (failed) or Replay (delivered), and Retry failed… gives every failed delivery of a period one more attempt at once, up to 1,000 per go, the oldest first. The API retries one at a time (
POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry). A retry or replay sends the samewebhook-idand body; onlywebhook-timestampand the signature are new, so the five-minute check keeps working. One that fails again staysfailed. Events from while the endpoint was paused were never queued, so no retry brings them back. Retries by hand are in the organization's audit log. - IP addresses. Deliveries come from Postilio's servers in the EU. There is no fixed, published IP range yet, so do not allow them by IP address: verify the signature.
- Requests carry
User-Agent: Postilio-Webhooks/1.0,Content-Type: application/jsonand no cookies or credentials.
Verifying the signature
Every request has three headers:
| Header | Content |
|---|---|
webhook-id | the event id: drop repeats by it |
webhook-timestamp | when it was sent, in Unix seconds |
webhook-signature | v1, 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();
});