Skip to content

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.

Request
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"] } } }
Webhook message fields
FieldWhat it holds
idStable message id. Your idempotency key, and the id for the message API.
fromThe address in the From header: the sender a person means.
envelope_fromThe SMTP envelope sender, often a bounce address. For bounce handling, not display.
toThe receiving inbox.
text_content, html_contentThe decoded bodies. Either can be null.
headersParsed message headers as an object.
extractedcodes: 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:

Terminal
# 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:

  1. Read the body as raw bytes, before any JSON parsing.
  2. Compute sha256= + hex(HMAC-SHA256(secret, body)).
  3. Compare with the header in constant time. Reject with 401 on mismatch.
  4. Only then parse the JSON.
Node.js (Express)
// 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);

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:

Webhook retry schedule
AttemptWhen
1As soon as the message is stored
230 seconds after a failure
35 minutes later
430 minutes later
52 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.

SQL
-- 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 stop

Insert 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 to when one webhook covers several inboxes: invoices@… to accounting, signup-bot@… to your agent.
  • Trust from for 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 to text_content when it is empty: extraction is a heuristic and leaves arrays empty rather than guess.
  • Hand text_content to 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.

Get every inbound email as signed JSON

Create an account, add an inbox and a webhook, and verify your first delivery with the dashboard's test event.

Receive-only. Paid plans, by card, cancel any time.