Guide · Webhooks
Parse inbound email to JSON with signed webhooks
You want every email sent to an address to arrive in your code as a JSON object: sender, subject, text, HTML, headers, and any one-time code or link already pulled out. No MIME parser, no IMAP, no mail server.
RESTAPI.email does the receiving and parsing, then POSTs each message to your HTTPS endpoint with an HMAC signature. This guide covers the payload, verifying the signature in Node.js, Python and Web Crypto runtimes, and the two things production handlers get wrong: retries and duplicates.
Last reviewed:
What your endpoint receives
Each delivery is a POST with a JSON body and two headers of ours: the event name and the signature.
POST /hooks/email
Content-Type: application/json
X-Restapi-Email-Event: message.received
X-Restapi-Email-Signature: sha256=<hex HMAC-SHA256 of the raw body>
{ "event": "message.received",
"message": { "id": "...", "from": "sender@example.com",
"envelope_from": "bounce+abc123@mail.example.com",
"to": "my-agent@agent.restapi.email", "subject": "Example",
"text_content": "...", "html_content": "...",
"headers": { "subject": "Example" }, "status": "received",
"received_at": "2026-11-19T12:00:00.000Z",
"extracted": { "codes": ["582014"],
"links": ["https://example.com/verify?token=abc"] } } }| Field | What it holds |
|---|---|
id | Stable message id. Your idempotency key, and the id for the message API. |
from | The address in the From header: the sender a person means. |
envelope_from | The SMTP envelope sender, often a bounce address. For bounce handling, not display. |
to | The receiving inbox. |
text_content, html_content | The decoded bodies. Either can be null. |
headers | Parsed message headers as an object. |
extracted | codes: likely one-time codes, best first, at most 5. links: verification-looking links first, at most 20, with Gmail, Outlook and Proofpoint wrappers unwrapped. |
Raw MIME is not in the payload; fetch GET /api/v1/emails/{address}/messages/{id} when you need it. File attachments are discarded before storage, and messages over 1 MB are rejected at delivery, so do not build an attachment pipeline on this.
Create the webhook
In the dashboard, add a webhook for one inbox or for all of them. Only https:// URLs on public hosts are accepted. The signing secret is shown once: store it as RESTAPI_EMAIL_WEBHOOK_SECRET in your secret manager straight away. An agent holding an sk_agent_ key can register one for its own inbox:
# With an agent key: a webhook for this inbox (secret shown once)
curl -X POST "https://api.restapi.email/api/v1/emails/my-agent@agent.restapi.email/webhooks" \
-H "X-API-Key: sk_agent_..." -H "Content-Type: application/json" \
-d '{"url": "https://example.com/hooks/email"}'The dashboard can also send a signed test delivery. Its event is webhook.test, not message.received, so a handler that checks the event name will never mistake it for real mail.
Verify the HMAC signature
X-Restapi-Email-Signature is sha256= followed by the lowercase hex HMAC-SHA256 of the raw request body, keyed with the webhook secret. To verify:
- Read the body as raw bytes, before any JSON parsing.
- Compute sha256= + hex(HMAC-SHA256(secret, body)).
- Compare with the header in constant time. Reject with 401 on mismatch.
- Only then parse the JSON.
// npm install express
import crypto from 'node:crypto';
import express from 'express';
const SECRET = process.env.RESTAPI_EMAIL_WEBHOOK_SECRET;
const seen = new Set(); // use your database in production
function validSignature(rawBody, header) {
const expected = 'sha256=' +
crypto.createHmac('sha256', SECRET).update(rawBody).digest('hex');
return typeof header === 'string' &&
header.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
}
const app = express();
// express.raw keeps the exact bytes; express.json() would break the HMAC
app.post('/hooks/email', express.raw({ type: 'application/json', limit: '5mb' }), (req, res) => {
if (!validSignature(req.body, req.get('X-Restapi-Email-Signature'))) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString('utf8'));
if (event.event !== 'message.received') return res.sendStatus(204); // e.g. webhook.test
const { message } = event;
if (seen.has(message.id)) return res.sendStatus(204); // duplicate delivery
seen.add(message.id);
// Answer within five seconds; do slow work after responding or on a queue.
res.sendStatus(204);
handleEmail(message);
});
function handleEmail(message) {
console.log(message.from, message.subject, message.extracted.codes);
}
app.listen(3000);# pip install fastapi uvicorn
import hashlib, hmac, json, os
from fastapi import BackgroundTasks, FastAPI, Request, Response
SECRET = os.environ["RESTAPI_EMAIL_WEBHOOK_SECRET"].encode()
seen: set[str] = set() # use your database in production
app = FastAPI()
def valid_signature(raw_body: bytes, header: str | None) -> bool:
expected = "sha256=" + hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(header or "", expected)
def handle_email(message: dict) -> None:
print(message["from"], message["subject"], message["extracted"]["codes"])
@app.post("/hooks/email")
async def hook(request: Request, tasks: BackgroundTasks):
raw = await request.body() # the exact bytes, before json.loads
if not valid_signature(raw, request.headers.get("x-restapi-email-signature")):
return Response(status_code=401)
event = json.loads(raw)
if event["event"] != "message.received": # e.g. webhook.test
return Response(status_code=204)
message = event["message"]
if message["id"] in seen: # duplicate delivery
return Response(status_code=204)
seen.add(message["id"])
tasks.add_task(handle_email, message) # runs after the 204 is sent
return Response(status_code=204)// Cloudflare Workers, Next.js route handlers, Deno, Bun: Web Crypto
const enc = new TextEncoder();
// process.env.X in Next.js and Bun, env.X in a Worker, Deno.env.get('X') in Deno
const SECRET = process.env.RESTAPI_EMAIL_WEBHOOK_SECRET;
async function validSignature(rawBody, header, secret) {
const match = /^sha256=([0-9a-f]{64})$/.exec(header ?? '');
if (!match) return false;
const sig = new Uint8Array(match[1].match(/../g).map((h) => parseInt(h, 16)));
const key = await crypto.subtle.importKey(
'raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'],
);
return crypto.subtle.verify('HMAC', key, sig, enc.encode(rawBody)); // constant time
}
export async function POST(request) {
const raw = await request.text();
const ok = await validSignature(
raw, request.headers.get('X-Restapi-Email-Signature'), SECRET,
);
if (!ok) return new Response(null, { status: 401 });
const event = JSON.parse(raw);
if (event.event === 'message.received') {
// enqueue event.message, keyed by event.message.id
}
return new Response(null, { status: 204 });
}Works where the runtime provides crypto.subtle and the Fetch Request: Cloudflare Workers, Next.js route handlers, Deno, Bun.
The bug everyone hits once
A framework parses the JSON for you, and you hash JSON.stringify(req.body). The re-serialised string differs from what was signed (key order, whitespace, escaped characters), so valid deliveries fail. Hash the bytes you received. In Express that means express.raw() on this route; in FastAPI, await request.body(); in Flask, request.get_data().
Retries: answer fast, work later
A delivery succeeds when your endpoint answers with any 2xx within five seconds. Anything else, a timeout, a 4xx or a 5xx, counts as a failure and is retried on a schedule:
| Attempt | When |
|---|---|
| 1 | As soon as the message is stored |
| 2 | 30 seconds after a failure |
| 3 | 5 minutes later |
| 4 | 30 minutes later |
| 5 | 2 hours later; no more attempts after this |
That is five attempts over roughly three hours. Every attempt is recorded with its status and error in the delivery log (the dashboard, or GET /api/webhooks/{id}/deliveries). If your endpoint was down longer than that, nothing is lost: the message stays readable over the REST API for 30 days, so a catch-up job can list everything since the last id you processed.
Five seconds is short for real work such as calling an LLM, writing to three systems or rendering a PDF. Verify, record the message, answer 204, and do the rest in the background or on a queue. Redirects are followed for up to three hops (each re-checked as https:// and public) but share the same five seconds, so register the final URL.
Idempotency: expect the same message twice
Retries mean at-least-once delivery. If your handler did its work but answered after the five-second limit, the attempt is recorded as failed and the same message arrives again. The signature covers the body only and carries no timestamp, so a captured request could also be replayed. Both cases have the same fix: the message.id is stable, so record it and ignore repeats.
-- Postgres: one row per message; a duplicate delivery inserts nothing
CREATE TABLE inbound_email (
message_id text PRIMARY KEY,
received_at timestamptz NOT NULL,
payload jsonb NOT NULL,
processed boolean NOT NULL DEFAULT false
);
INSERT INTO inbound_email (message_id, received_at, payload)
VALUES ($1, $2, $3)
ON CONFLICT (message_id) DO NOTHING
RETURNING message_id; -- no row back: already seen, answer 2xx and stopInsert first, act only when the insert created a row, and answer 2xx for duplicates too: they are not errors, and a non-2xx answer would only schedule another retry.
Routing and parsing ideas
- Route on
towhen one webhook covers several inboxes:invoices@…to accounting,signup-bot@…to your agent. - Trust
fromfor display, not for authorisation: headers can be forged. Use a secret token in the address or the subject when it matters. - Use
extracted.codes[0]for OTP flows, but fall back totext_contentwhen it is empty: extraction is a heuristic and leaves arrays empty rather than guess. - Hand
text_contentto an LLM for structured extraction of orders or forms, and treat the text as untrusted input.
Would you rather pull than be pushed? The same messages are available over REST with long-poll; see the Playwright guide for the pattern.
Questions
Which header carries the webhook signature?
X-Restapi-Email-Signature, in the form sha256= followed by the hex HMAC-SHA256 of the raw request body, keyed with the webhook secret shown once when the webhook is created. X-Restapi-Email-Event names the event.
Why does my signature check fail when the secret is right?
Almost always because the body was parsed and re-serialised before hashing. Compute the HMAC over the exact bytes received, before JSON parsing, and compare in constant time.
How often is a failed delivery retried?
Any non-2xx answer or a timeout (five seconds per attempt) is retried after 30 seconds, 5 minutes, 30 minutes and 2 hours: five attempts in all. Every attempt is recorded in the delivery log.
Can the same email be delivered twice?
Plan for it. A retry after a slow 2xx, or a replayed request, carries the same message.id, so store the ids you have processed and skip repeats.