Email webhooks vs polling: four ways an agent learns that mail arrived
An agent can learn that mail arrived in four ways: poll a list on a timer, hold a request open until mail arrives (a long poll), receive a signed webhook at a public URL, or read a live event stream. Use a long poll for one expected email, webhooks for a server, and a stream when no public URL exists.
Updated
What are the ways to learn that mail arrived?
There are four ways for a program to learn that mail arrived: polling, a long poll, a webhook and a live event stream. They differ in who opens the connection and how long it stays open.
| Method | How it works | Delay | Needs a public URL | Fits |
|---|---|---|---|---|
| Polling | Ask a list endpoint for new mail on a timer | Up to one interval | No | Batch jobs, catching up after downtime |
| Long poll | One request stays open until mail arrives or a timeout passes | Close to none | No | An agent waiting for one email |
| Webhook | The mail service posts each event to your HTTPS endpoint | Close to none | Yes | A server that handles mail all day |
| Live stream | One long connection carries each event as it happens | Close to none | No | A worker behind a firewall, local development |
When is polling enough?
Polling is enough when a delay of one interval does not matter and the number of inboxes is small. It needs no public endpoint and no signature check, and a poller that crashed picks up where it stopped if it saved the last item it saw.
The cost is that most requests return nothing. Delay and request count pull against each other: halve the interval and you double the requests, for every inbox you watch. Poll with a cursor, not a timestamp, so nothing is skipped and nothing is read twice.
With Trotta Mail, poll the event log with the id of the last event you handled. With after, events come back oldest first:
import os
import time
import requests
API = "https://api.trotta.email/ v1"
HEADERS = {"Authorization": f"Bearer {os.environ['TROTTA_MAIL_API_KEY']}"}
# load_cursor, save_cursor and handle are your own functions.
last_seen = load_cursor() # the id of the last event you handled, such as "evt_1Vb6kRs3"
while True:
page = requests.get(
f"{API}/ events",
params={"after": last_seen, "types": "message.received"},
headers=HEADERS,
timeout=30,
).json()
for event in page["data"]:
handle(event)
last_seen = event["id"]
save_cursor(last_seen)
time.sleep(30)What is a long poll, and when should an agent use one?
A long poll is a single request that the server holds open until there is something to return. An agent should use one when it expects a specific email: a verification code, or a reply to a message it just sent. The code reads like a blocking call, and there is nothing to host.
import { TrottaMail } from "trotta-mail";
const mail = new TrottaMail({ apiKey: process.env.TROTTA_MAIL_API_KEY });
// Returns as soon as a matching message is delivered, or null on a timeout.
const msg = await mail.inboxes.wait("inb_7Qh2mXc4", { from: "harbor.example", timeout: 60 });
if (msg) console.log(msg.subject, msg.extracted.codes);Behind it is GET /v1/inboxes/{id}/wait. One request holds for up to 60 seconds and filters by from, subject, has_code and after. On a timeout it returns { "message": null, "timed_out": true }: call it again. It returns delivered mail, never held mail.
Sending can wait too. Add "wait_for_reply": 60 to a send and the call blocks until the answer arrives, which comes back as reply.
How do email webhooks work?
An email webhook is an HTTP POST that the mail service sends to your endpoint when something happens. You register an HTTPS URL, choose the event types, and answer each delivery with a 2xx status.
curl -X POST https://api.trotta.email/ v1/ webhooks \
-H "Authorization: Bearer $TROTTA_MAIL_API_KEY" \
-H "Content-Type: application/ json" \
-d '{"url": "https://example.com/ hooks/ trotta-mail", "event_types": ["message.received", "message.held"]}'The answer includes a secret that starts with whsec_. Store it: it is shown once, and POST /v1/webhooks/{id}/rotate-secret returns a new one. The key needs the admin scope. Leave out event_types and you get message.received alone. Add inbox_id to hear about one inbox.
The body of each request is an event with its id, its type and the message. The message is the safe view, so it can go to a model without a second fetch. For held mail it is withheld: where it is and why, and nothing its sender wrote.
How do you verify a webhook signature?
Verify a webhook by computing its signature again over the raw request body with your secret, and comparing the two in constant time. Anyone can find a public URL and post to it, so a webhook that is not verified is an open door into your agent.
Trotta Mail follows the Standard Webhooks scheme. Each request carries webhook-id, webhook-timestamp (unix seconds) and webhook-signature. The signature is HMAC-SHA256 over {id}.{timestamp}.{body}, keyed with the base64 part of the secret. Check the timestamp too, and refuse old requests, so a captured request cannot be replayed later.
import express from "express";
import { TrottaMail } from "trotta-mail";
const mail = new TrottaMail({ apiKey: process.env.TROTTA_MAIL_API_KEY });
const secret = process.env.TROTTA_MAIL_WEBHOOK_SECRET ?? "";
const handled = new Set<string>(); // keep these in a database or a cache in production
const app = express();
// express.raw keeps the exact bytes that were signed.
app.post("/ hooks/ trotta-mail", express.raw({ type: "application/ json" }), async (req, res) => {
let event;
try {
event = await mail.webhooks.verify(req.body.toString(), req.headers, secret);
} catch {
return res.status(400).send("Bad signature");
}
const id = String(req.headers["webhook-id"]);
if (handled.has(id)) return res.sendStatus(200); // a retry of something already handled
handled.add(id);
res.sendStatus(200); // acknowledge first, then do the slow work
if (event.type === "message.received") {
// event.data.message is the safe view.
console.log(event.data.message?.subject);
}
});
app.listen(3000);Without the SDK, the check is a few lines in any language. In Python:
import base64, hashlib, hmac, json, time
def verify(raw_body: bytes, headers: dict, secret: str) -> dict:
msg_id = headers["webhook-id"]
timestamp = headers["webhook-timestamp"]
# Refuse anything older than five minutes.
if abs(time.time() - int(timestamp)) > 300:
raise ValueError("Stale webhook")
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = f"{msg_id}.{timestamp}.".encode() + raw_body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
for part in headers.get("webhook-signature", "").split(" "):
version, _, signature = part.partition(",")
if version == "v1" and hmac.compare_digest(signature, expected):
return json.loads(raw_body)
raise ValueError("Bad signature")Verify against the raw body, before any JSON parsing. A framework that parses the body and writes it out again changes the bytes, and the signature stops matching.
What happens when a webhook delivery fails?
A failed webhook delivery is retried, so a receiver must expect the same event more than once. Trotta Mail treats anything other than a 2xx answer, or no answer, as a failure. It retries after 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours and 8 hours. Redirects are never followed.
- Answer fast. Acknowledge with a 2xx, then call the model or send the reply from a queue.
- Ignore duplicates. The
webhook-idstays the same across retries. Record the ids you have handled and skip repeats. - Catch up after downtime. Events stay in the log. Page through
GET /v1/events?after=evt_...from the last event you handled. - Replay by hand.
GET /v1/webhooks/{id}/deliveriesshows what was sent and how your endpoint answered.POST /v1/webhooks/deliveries/{id}/replaysends one again. - Test first.
POST /v1/webhooks/{id}/testsends a signed samplemessage.received.
When is a live event stream the better choice?
A live event stream is the better choice when the agent has no public URL: a laptop, a worker behind a firewall, a container that takes no inbound traffic. The agent opens one outbound connection, and events arrive on it as they happen.
Trotta Mail serves the stream as server-sent events at GET /v1/events/stream, and the same events over a WebSocket at /v1/events/ws. Narrow either with inbox_id and types. The key goes in the Authorization header, never in the URL.
curl -N "https://api.trotta.email/ v1/ events/ stream?types=message.received,message.held" \
-H "Authorization: Bearer $TROTTA_MAIL_API_KEY"event: message.received
id: evt_1Vb6kRs3
data: {"id":"evt_1Vb6kRs3","type":"message.received","inbox_id":"inb_7Qh2mXc4","data":{...}}A stream drops when the network does. Reconnect with the Last-Event-ID header set to the last id you saw, and the stream continues from there. The live events docs show how to read it in code.
Polling, long poll, webhook or stream: which should an agent use?
An agent should use the simplest method that meets its delay and hosting limits.
- One expected email, such as a code or a reply: the long poll.
- A server that handles all mail: webhooks, with the event log as the backstop.
- No public URL: the live stream.
- A nightly job or a prototype: polling.
Many systems pair two: webhooks for speed, and a scheduled poll of the event log to catch anything that was missed.
Whichever method an agent uses with Trotta Mail, it carries the same screened view. Every message is checked before it is delivered, held mail is withheld on every channel, and sealed login mail from a human's mailbox never reaches a webhook or a key reading the stream. The webhooks docs list every event type.
Questions
Are webhooks faster than polling?
Yes, in most setups. A webhook is sent as the event happens, while polling waits up to one interval. A long poll or a live stream is as quick as a webhook and needs no public URL.
Do I need a public URL to receive email events?
Only for webhooks. A long poll and an event stream run over outbound connections, so they work from a laptop or behind a firewall.
Can a webhook deliver the same email event twice?
Yes. Retries mean an event can arrive more than once, so record each webhook-id you handle and skip repeats.
How many webhooks can I create in Trotta Mail?
One on the Free plan, and no limit on Developer, Startup and Enterprise. Past the limit, creating one answers 403 webhook_limit_reached.
Does a webhook include the whole email?
It includes the message in the safe view: visible text, with hidden text removed and risky links defanged. For held mail the event says where the message is and why, and carries nothing its sender wrote.