Webhook to Send Email: Trigger Outbound Mail in One Call
Turn any webhook (Stripe, GitHub, forms) into an outbound email: verify the signature, dedupe retries, and send with one API call in Node or Python.
John Joubert
Founder, Robotomail

Table of contents
To use a webhook to send email, point the external app's webhook at a small endpoint you control. That endpoint verifies the signature, records the event ID so retries can't send twice, and then makes one POST to an email API. The whole handler fits in about 40 lines. The hard parts are the security and the duplicate handling, not the send itself.
This guide covers outbound only: an event happens somewhere else (a form submission, a Stripe payment, a GitHub push, any JSON POST) and your code sends an email in response.
The shape of a webhook-to-send-email handler
Every handler in this pattern does four things in order:
- Read the raw body. Signature checks run on the exact bytes the sender signed, before any JSON parsing.
- Verify the event. Reject anything that isn't signed with your shared secret.
- Claim the event ID. Write it to durable storage with a unique constraint. If the write conflicts, you've already handled this event. Return 200 and stop.
- Send the email and acknowledge. Make the API call, record the result, and return 2xx.
You need a mailbox to send from first. Create one once:
npx @robotomail/cli mailbox create order-notifier
That gives the agent a real address that can also receive replies. Most hand-rolled notification setups lack this. A customer who answers "wrong address, please fix" reaches a real inbox and doesn't bounce off a no-reply address.
Step 1: Verify the incoming event
Never send email from an unauthenticated endpoint. A public URL that sends mail when it receives a POST is an open relay with extra steps. Anyone who finds it can make you email arbitrary content, and your sending reputation pays for it.
Most webhook senders sign the request with an HMAC-SHA256 over the raw body using a secret you both know:
- GitHub sends the signature in the
X-Hub-Signature-256header assha256=<hex>. It identifies each delivery withX-GitHub-Delivery. - Stripe sends a
Stripe-Signatureheader that includes a timestamp and a signature over the timestamp plus the body. Use Stripe's official library to verify it, and reject events whose timestamp is too old. That blocks replay attacks. - Plain form backends and internal services often don't sign anything. Add a long random token in a header and check it. Put the form behind whatever spam protection you already use.
Three rules apply regardless of the sender:
- Compute the HMAC over the raw bytes. Parsing and re-serializing JSON changes whitespace and key order, which breaks the signature.
- Compare with a constant-time function (
crypto.timingSafeEqual,hmac.compare_digest). - Don't let the payload choose the recipient freely. If the event says "email
customer_email", check that the address belongs to a record you own, such as the customer on that order. Otherwise a forged or tampered event turns your handler into a spam cannon.
Step 2: Deduplicate so retries don't send twice
Webhook senders retry. They retry when you time out, when you return a 5xx, and sometimes when nothing went wrong at all. Delivery is at-least-once, so your handler has to make the send effectively once.
The reliable pattern is a table with a unique key on the event ID:
CREATE TABLE processed_events (
event_id TEXT PRIMARY KEY,
status TEXT NOT NULL, -- 'sending' | 'sent' | 'unknown'
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Claim the ID with INSERT ... ON CONFLICT DO NOTHING before sending. If the insert returns no row, another delivery already took it, so acknowledge and exit.
The edge cases matter more than the happy path:
- The send fails with a clear error response. Delete the claim and return a 5xx so the sender retries. Check the Robotomail errors reference to tell a retryable error from a permanent one, like an invalid recipient. Don't release the claim on a permanent error.
- The send times out. You don't know whether the email went out. Mark the row
unknownand alert, instead of releasing it and risking a duplicate. A human checking one ambiguous event is cheaper than a customer getting the same invoice twice. - Your process crashes mid-send. You get a row stuck in
sending. Sweep those periodically and handle them the same way asunknown.
Use the sender's own event ID when it has one: Stripe's event id, GitHub's X-GitHub-Delivery. For forms, use the submission ID, or a hash of the normalized fields if nothing else exists.
Step 3: The send request in Node
This is an Express handler for a signed JSON webhook. db is any Postgres client.
import express from "express";
import crypto from "node:crypto";
const app = express();
const SECRET = process.env.WEBHOOK_SECRET!;
const RM_KEY = process.env.ROBOTOMAIL_API_KEY!;
const mailboxId = process.env.ROBOTOMAIL_MAILBOX_ID!;
app.post("/hooks/orders", express.raw({ type: "application/json" }), async (req, res) => {
// 1. Verify signature over raw bytes
const sig = Buffer.from(req.header("x-signature") ?? "");
const expected = Buffer.from(
crypto.createHmac("sha256", SECRET).update(req.body).digest("hex")
);
if (sig.length !== expected.length || !crypto.timingSafeEqual(sig, expected)) {
return res.sendStatus(401);
}
const event = JSON.parse(req.body.toString("utf8"));
// 2. Claim the event ID
const claim = await db.query(
"INSERT INTO processed_events (event_id, status) VALUES ($1, 'sending') ON CONFLICT DO NOTHING RETURNING event_id",
[event.id]
);
if (claim.rowCount === 0) return res.sendStatus(200); // duplicate delivery
// 3. Send
try {
const r = await fetch(`https://api.robotomail.com/v1/mailboxes/${mailboxId}/messages`, {
method: "POST",
headers: { Authorization: `Bearer ${RM_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
to: [event.customer_email], // validated against your order record in real code
subject: `Order ${event.order_id} confirmed`,
bodyText: `Thanks, we received order ${event.order_id}. Reply to this email with any questions.`,
}),
signal: AbortSignal.timeout(10_000),
});
if (!r.ok) {
await db.query("DELETE FROM processed_events WHERE event_id = $1", [event.id]);
return res.sendStatus(502);
}
await db.query("UPDATE processed_events SET status = 'sent' WHERE event_id = $1", [event.id]);
return res.sendStatus(200);
} catch {
await db.query("UPDATE processed_events SET status = 'unknown' WHERE event_id = $1", [event.id]);
return res.sendStatus(200); // don't invite a retry that could double-send
}
});
Step 4: The same handler in Python
Here it is in Flask. claim, release, and mark wrap the same SQL as the Node version.
import hashlib, hmac, os
import requests
from flask import Flask, request
app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].encode()
RM_KEY = os.environ["ROBOTOMAIL_API_KEY"]
MAILBOX_ID = os.environ["ROBOTOMAIL_MAILBOX_ID"]
@app.post("/hooks/orders")
def orders():
raw = request.get_data()
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, request.headers.get("X-Signature", "")):
return "", 401
event = request.get_json()
if not claim(event["id"]):
return "", 200 # already handled
try:
r = requests.post(
f"https://api.robotomail.com/v1/mailboxes/{MAILBOX_ID}/messages",
headers={"Authorization": f"Bearer {RM_KEY}"},
json={
"to": [event["customer_email"]],
"subject": f"Order {event['order_id']} confirmed",
"bodyText": f"Thanks, we received order {event['order_id']}.",
},
timeout=10,
)
except requests.RequestException:
mark(event["id"], "unknown")
return "", 200
if r.status_code >= 400:
release(event["id"])
return "", 502
mark(event["id"], "sent")
return "", 200
If you haven't made a send call before, the send your first email guide walks through API keys and mailbox IDs.
When to queue instead of sending inline
The inline handler works because a single API call is fast. Move the send to a background job when the email needs slow work first, such as rendering a PDF, calling an LLM to draft a summary, or looking up several records. In that case the handler verifies, claims, enqueues, and returns 200 right away. The worker does the send and updates the status row. The deduplication logic stays the same, it just runs in the worker.
This is the usual shape for order and billing flows. See how it fits ecommerce order emails where an agent sends the confirmation and then handles the replies.
FAQ
Should the email come from a no-reply address?
Usually not. A real mailbox lets customers reply, and your agent can process those replies. Using an agent-owned address is the main reason to choose an email API built for AI agents over a bare relay.
Do I need a custom domain?
Not to start. Mailboxes on the platform domain work right away. For production customer-facing mail, add your own domain so recipients see your brand.
How many emails can I send?
It depends on your plan. Solo ($5/month) includes one mailbox, one custom domain, 500 sends and 500 receives per month. Higher tiers raise those limits.
Can a webhook-triggered email continue an existing thread?
Yes. When you're replying to a message the mailbox received, include inReplyTo with that inbound message ID and the reply threads correctly. A fresh notification like an order confirmation is just a new message.
Ready to wire your first event to an outbound email? Start with Robotomail and have a sending mailbox in a minute.
Give your AI agent a real email address
Create a mailbox, connect your agent and test a conversation. Send, receive and retrieve the thread through one API.
Related posts

Lead Qualification with the Python SDK for SaaS Teams
Build multi-customer lead qualification with the Python SDK: per-customer mailboxes, verified webhooks, threaded follow-ups and clean human handoff.
Read post
Migrate from AgentMail to Robotomail: Worked Example
Move one agent inbox workflow from AgentMail to Robotomail: map operations, port an adapter, test replies and webhooks, then stage rollout and rollback.
Read post
What Is Agentic Mail? A Developer's Guide
Agentic mail is email infrastructure for AI agents: real mailboxes, inbound webhooks, threading. What it is, how it differs from an email API, with code.
Read post