Skip to content

Webhooks

A webhook is an HTTP POST request FrontEngine makes to your system when something happens to a message or to the server. It is the recommended way to follow deliveries.

The event format, the signature and the retry schedule follow Postal's, so receivers written for Postal keep working.

Configuration

Webhooks are configured per server, by our team. Write to [email protected] with:

  • the URL of your endpoint (use HTTPS);
  • the events you want to receive, or all of them.

Endpoint requirements:

  • It must be at a public address. URLs that resolve to private, loopback or link-local addresses are refused.
  • It must answer within 5 seconds.
  • Redirects are not followed. Give the final URL.

Event types

Event When it happens
MessageSent The destination server accepted the message.
MessageDelayed Delivery failed temporarily and will be retried.
MessageDeliveryFailed Delivery failed permanently, or retries were exhausted.
MessageHeld The message was held because the recipient is on the suppression list.
MessageBounced A bounce arrived by email for a message the destination had already accepted.
MessageLoaded The message was opened (the tracking image was loaded).
MessageLinkClicked A tracked link was clicked.
SendLimitApproaching The server reached nine tenths of its hourly send limit.
SendLimitExceeded The server went over its hourly send limit.
DomainDNSError A DNS record of a verified domain stopped checking out.

Notes:

  • MessageLoaded and MessageLinkClicked happen only on servers with a tracking domain configured by our team.
  • SendLimitApproaching and SendLimitExceeded happen only on servers with an hourly limit set, at most once an hour each. Messages above the limit are accepted and held, not refused.
  • There is no spam complaint event.

Request format

POST /your/endpoint HTTP/1.1
Content-Type: application/json
User-Agent: Postal/<version>
X-Postal-Signature: <RSA-SHA1 signature, base64>
X-Postal-Signature-256: <RSA-SHA256 signature, base64>
X-Postal-Signature-KID: <key identifier>

Every event has the same envelope:

{
  "event": "MessageSent",
  "timestamp": 1764331205.412,
  "uuid": "6f1d2c9a-0c1e-4a57-9a53-3b0e0e6f2d11",
  "payload": {}
}
Field Description
event Event type.
timestamp When the event was generated, in Unix seconds with a fraction.
uuid Unique identifier of the event. Retries carry the same uuid.
payload Event data. The shape depends on the type.

Payloads

The message object

It appears in message events:

{
  "id": 1042,
  "token": "Zp3kQ9xT",
  "direction": "outgoing",
  "message_id": "[email protected]",
  "to": "[email protected]",
  "from": "[email protected]",
  "subject": "Order 1234 confirmed",
  "timestamp": 1764331203.118,
  "spam_status": "NotChecked",
  "tag": "order-confirmed"
}

id and token are the ones returned on send. tag is null when the message has no tag. spam_status is always NotChecked.

MessageSent, MessageDelayed, MessageDeliveryFailed, MessageHeld

{
  "event": "MessageDelayed",
  "timestamp": 1764331205.412,
  "uuid": "6f1d2c9a-0c1e-4a57-9a53-3b0e0e6f2d11",
  "payload": {
    "message": { "id": 1042, "token": "Zp3kQ9xT", "to": "[email protected]" },
    "status": "SoftFail",
    "details": "Delivery to [email protected] was deferred and will be retried",
    "output": "451 4.7.1 Try again later",
    "sent_with_ssl": true,
    "timestamp": 1764331205.398,
    "time": null
  }
}
Field Description
status Sent, SoftFail, HardFail or Held, according to the event.
details Description of the outcome, written by FrontEngine.
output The destination server's reply, limited to 512 characters.
sent_with_ssl true if the connection to the destination used TLS.
timestamp Time of the attempt.
time Always null.

In the examples, the message object is abbreviated. It always arrives complete.

MessageBounced

{
  "event": "MessageBounced",
  "timestamp": 1764334810.007,
  "uuid": "b0a1c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
  "payload": {
    "original_message": { "id": 1042, "token": "Zp3kQ9xT", "to": "[email protected]" },
    "bounce": {
      "id": 0,
      "token": "f3a9c2e1",
      "direction": "incoming",
      "message_id": "[email protected]",
      "to": "[email protected]",
      "from": "[email protected]",
      "subject": "Undelivered Mail Returned to Sender",
      "timestamp": 1764334809.731,
      "spam_status": "NotChecked",
      "tag": null
    }
  }
}

original_message is the message you sent. bounce describes the return email received; its id is always 0.

MessageLoaded and MessageLinkClicked

{
  "event": "MessageLinkClicked",
  "timestamp": 1764335001.220,
  "uuid": "0d9c8b7a-6f5e-4d3c-b2a1-9f8e7d6c5b4a",
  "payload": {
    "message": { "id": 1042, "token": "Zp3kQ9xT", "to": "[email protected]" },
    "ip_address": "203.0.113.7",
    "user_agent": "Mozilla/5.0",
    "url": "https://www.yourdomain.com/orders/1234",
    "token": "k2J8sLq0"
  }
}

url and token (the link's) exist only in MessageLinkClicked.

Do not rely on ip_address

Today the address recorded in these two events is not the reader's. Do not use this field for geolocation or for security decisions. Remember too that opens are an imprecise signal: mail clients and filters load images and follow links automatically.

SendLimitApproaching and SendLimitExceeded

{
  "event": "SendLimitApproaching",
  "timestamp": 1764331800.000,
  "uuid": "c7d6e5f4-a3b2-4c1d-9e8f-7a6b5c4d3e2f",
  "payload": {
    "server": {
      "uuid": "server-token",
      "name": "store-production",
      "permalink": "store-production",
      "organization": "my-company"
    },
    "volume": 905,
    "limit": 1000
  }
}

volume is the amount sent in the current hour and limit is the server's hourly limit.

DomainDNSError

{
  "event": "DomainDNSError",
  "timestamp": 1764374400.000,
  "uuid": "e1f2a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b",
  "payload": {
    "domain": "yourdomain.com",
    "uuid": "domain-verification-token",
    "dns_checked_at": 1764374399.512,
    "server": {
      "uuid": "server-token",
      "name": "store-production",
      "permalink": "store-production",
      "organization": "my-company"
    },
    "spf_status": "OK",
    "spf_error": null,
    "dkim_status": "OK",
    "dkim_error": null,
    "mx_status": "OK",
    "mx_error": null,
    "return_path_status": "Invalid",
    "return_path_error": "points at other.example.net"
  }
}

Each *_status is OK, Missing, Invalid, Error, Unconfigured or Unchecked. The matching *_error carries the detail or null. What each check means is in Set up a sending domain.

Signature verification

Every request is signed with FrontEngine's private RSA key over the raw body of the request (PKCS#1 v1.5). The public key is at:

https://api.frontengine.net/.well-known/jwks.json
Header Content
X-Postal-Signature-256 RSA-SHA256 signature, base64. Use this one.
X-Postal-Signature RSA-SHA1 signature, base64. It exists for compatibility with older receivers.
X-Postal-Signature-KID The kid of the key in the JWKS.

Rules for verifying correctly:

  • Verify the bytes exactly as they arrived, before any JSON.parse. Re-serializing the JSON changes the bytes and invalidates the signature.
  • Pick the JWKS key by the kid received in X-Postal-Signature-KID.
  • Cache the JWKS. Fetch it again only when an unknown kid arrives.
  • Refuse the request (HTTP 401) if the signature does not check out.
# pip install flask cryptography requests
import base64

import requests
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from flask import Flask, abort, request

JWKS_URL = "https://api.frontengine.net/.well-known/jwks.json"
app = Flask(__name__)
_keys = {}


def load_keys(jwks):
    keys = {}
    for k in jwks["keys"]:
        n = int.from_bytes(base64.urlsafe_b64decode(k["n"] + "=="), "big")
        e = int.from_bytes(base64.urlsafe_b64decode(k["e"] + "=="), "big")
        keys[k["kid"]] = rsa.RSAPublicNumbers(e, n).public_key()
    return keys


def verify(keys, body, signature_b64, kid):
    key = keys.get(kid)
    if key is None:
        return False
    try:
        key.verify(
            base64.b64decode(signature_b64), body, padding.PKCS1v15(), hashes.SHA256()
        )
        return True
    except (InvalidSignature, ValueError):
        return False


def keys_for(kid):
    global _keys
    if kid not in _keys:
        _keys = load_keys(requests.get(JWKS_URL, timeout=5).json())
    return _keys


@app.post("/webhooks/frontengine")
def webhook():
    body = request.get_data()  # raw bytes, before any parsing
    signature = request.headers.get("X-Postal-Signature-256", "")
    kid = request.headers.get("X-Postal-Signature-KID", "")
    if not verify(keys_for(kid), body, signature, kid):
        abort(401)

    event = request.get_json()
    enqueue(event["uuid"], event)  # process outside the request
    return "", 200


def enqueue(uuid, event):
    """Store the event in a queue or table, with uuid as the unique key."""
    print(uuid, event["event"])
// npm install express
const crypto = require("node:crypto");
const express = require("express");

const JWKS_URL = "https://api.frontengine.net/.well-known/jwks.json";
const app = express();
let keys = new Map();

function loadKeys(jwks) {
  const out = new Map();
  for (const jwk of jwks.keys) {
    out.set(jwk.kid, crypto.createPublicKey({ key: jwk, format: "jwk" }));
  }
  return out;
}

function verify(keys, body, signatureB64, kid) {
  const key = keys.get(kid);
  if (!key) return false;
  return crypto.verify("RSA-SHA256", body, key, Buffer.from(signatureB64, "base64"));
}

async function keysFor(kid) {
  if (!keys.has(kid)) {
    const res = await fetch(JWKS_URL, { signal: AbortSignal.timeout(5000) });
    keys = loadKeys(await res.json());
  }
  return keys;
}

// express.raw keeps the body as a Buffer, without re-serializing.
app.post(
  "/webhooks/frontengine",
  express.raw({ type: "application/json", limit: "1mb" }),
  async (req, res) => {
    const signature = req.get("X-Postal-Signature-256") || "";
    const kid = req.get("X-Postal-Signature-KID") || "";
    if (!verify(await keysFor(kid), req.body, signature, kid)) {
      return res.sendStatus(401);
    }
    const event = JSON.parse(req.body.toString("utf8"));
    enqueue(event.uuid, event); // process outside the request
    res.sendStatus(200);
  }
);

function enqueue(uuid, event) {
  // Store the event in a queue or table, with uuid as the unique key.
  console.log(uuid, event.event);
}

app.listen(3000);

Retries

A webhook delivery succeeds when your endpoint answers with any 2xx code within 5 seconds. Any other response, a timeout or a connection error counts as a failure.

Up to 6 attempts are made in total:

Attempt Wait after the previous failure
1 immediate
2 2 minutes
3 3 minutes
4 6 minutes
5 10 minutes
6 15 minutes

After the last failure the event is dropped and is not sent again. To recover the state of a specific message, use the status lookup.

Best practices

  • Answer 2xx fast. Validate the signature, store the event in a queue or table, and answer. Do the heavy processing later. Deliveries are made in sequence, and a slow endpoint delays the events that follow.
  • Handle duplicates. Delivery is at least once: the same event may arrive more than once. Use the uuid as the idempotency key and ignore what was already processed.
  • Do not depend on order. A retry may arrive after more recent events. Use the timestamp fields to order.
  • Ignore what you do not know. New event types and new fields may be added. Answer 2xx for events you do not handle.
  • Always verify the signature. The webhook URL is not a secret.
  • Monitor the endpoint. After 6 attempts the event is lost.

Next steps