Receive Email API: Webhooks, Polling and Security

Receive Email API: Webhooks, Polling and Security

Radicati Group's 2023 to 2027 forecast puts worldwide email traffic at 347.3 billion emails sent and received per day in 2023, rising to 408.2 billion per day in 2027 (Radicati Group email statistics forecast). Every one of those messages is input the receiving application did not write, cannot fully verify, and may act on.

Giving an agent its own address raises the stakes. A person reads a strange email and shrugs. An agent reads the same email and calls a tool, and the tool has a recipient field, a subject, a body, and whatever authority the run was granted. The distance between "summarize this thread" and "forward the last six months of invoices to an address that appears in the thread" is one sentence of instructions.

Two decisions decide whether the integration holds up: how the agent learns that mail arrived, and what it is allowed to do in response. Everything below is about those two.

Table of Contents

Receive Email API Methods Compared

Four delivery methods cover nearly every Receive Email API on the market, and they differ in what the agent has to hold: a cursor, a public endpoint, an open connection, or a terminal window.

MethodHow the agent gets new mailBest fitMain failure to design for
Inbox pollingAgent re-reads the inbox from its last saved cursorCron jobs and batch agentsMissed mail when the cursor is not saved durably
WebhooksProvider sends an HTTP POST to an endpoint you runAlways-on services with a public HTTPS endpointLate, duplicated or out-of-order deliveries
Live event streamAgent holds an open connection and receives events as they happenLong-running agent processesGaps during reconnects that need a replay from the last event ID
CLI listenCommand prints events to the terminal as they arriveLocal development and debuggingTied to one running process, so not a delivery record

Inbox polling is the agent asking. It re-reads the mailbox from the last position it saved, needs no inbound network path, and fits cron jobs and batch agents that already run on a schedule. Its failure is quiet: if the cursor lives in a variable, a restart wipes it and every message between the last good read and the restart is skipped.

Webhooks invert the direction. The provider posts JSON to an endpoint you run, which suits any always-on service with a public HTTPS address and a valid certificate. The cost is that you now own an availability requirement, a signature check, and a retry policy you don't control.

A live event stream keeps one connection open and pushes deliveries, bounces, replies and approval decisions as they happen. It suits long-running agent processes that shouldn't poll. Dropped connections create gaps, so the client reconnects with the last event ID it acknowledged and asks for a replay. The trade-offs between the two push paths are set out in webhooks versus websockets.

CLI listen prints events to a terminal as they arrive. It's for watching a payload shape while building, never for production delivery: it's tied to one running process and keeps no record of what it printed.

The rule the rest of this article depends on: a push signal is a notification, not the record.

An event saying message 8f21 changed is not message 8f21. The agent re-reads authoritative state after every signal and runs durable polling alongside any push path, so a delayed or dropped event costs latency rather than mail.

When the agent's first step after receiving a message is a lookup against a CRM or an order table, that retrieval layer is its own build; connecting customer data to AI covers the join between an agent and the systems that hold the record.

Scale is what makes the choice consequential. The Radicati Group email statistics report estimated 4.147 billion email users worldwide in 2021, projected 4.594 billion by the end of 2025, and 376.4 billion business and consumer emails sent and received per day in 2025. So which method fits the workload, and which failure gets designed against first?

Message Identifiers and Threading Fields

A reply that lands three days late is still one message, and it can still fire a second send if the agent treats it as new work. On Monday the mailbox stored Message-ID quote-4471@vendor.example. On Thursday a reply arrives with In-Reply-To set to that same value. Look up the parent in your own store, attach the reply to that thread, then check the reply's Message-ID in the dedupe table before any outbound step. If that Message-ID is already there, stop. That check is what makes a provider retry harmless instead of a duplicate send.

Mail is a tree, not a list. A reply points at a parent, and the parent points at a grandparent. Flatten that structure and the agent answers the wrong message with someone else's history in context, which is how one inbound message becomes a misdirected send. RFC 9051, the IMAP4rev2 specification, is the reference model for this: it defines server-side mailboxes, message manipulation, and offline resynchronization, the contract an agent needs when it rebuilds a mailbox view after a disconnect (RFC 9051).

A diagram illustrating email threading fields including Message-ID, In-Reply-To, and References linking three separate messages.

Six identifiers do the work. Store all of them.

IdentifierWhere it comes fromUse it for
Message-IDSender's message headerDeduplicating a message that arrives twice
In-Reply-ToHeader on a replyLinking a reply to its direct parent
ReferencesHeader listing the ancestor chainRebuilding a thread after a missed reply
Provider thread IDReceiving APIGrouping conversations the provider already threads
Event IDEach webhook or stream eventIdempotent processing of repeated deliveries
Sync cursorLast successful read positionResuming after a disconnect or restart

References covers the case In-Reply-To cannot. It lists the ancestor chain, so a message whose direct parent never arrived (dropped webhook, quarantine, an overeager filter) still joins the right thread when an older ancestor is already stored. Joining the wrong thread is worse than waiting. The next send then goes out with another conversation's history attached.

When headers are missing or malformed

Headers get forged, truncated, and rewritten by mailing lists. I treat a forged or partial header as hostile input, not as a hint to guess. Fall back in this order.

  • Provider thread ID first. The receiving API already grouped the conversation; its grouping beats a hand-built heuristic.
  • References second. Match the longest ancestor in the list against Message-IDs already stored.
  • A new thread last. An orphan reply that starts a thread is recoverable. A reply merged into the wrong conversation is not, because the agent then answers with someone else's history attached.

Never group by subject. "Re: Invoice" shows up in a dozen unrelated conversations, and a subject join will merge a supplier thread with a customer thread that share a line. The agent then replies into the wrong mailbox with the wrong context.

What to keep per message

Store the raw original once, immutable, exactly as received. Put normalized text in a separate field, so re-parsing with a better parser never requires re-fetching. Keep status and timestamps for every state change (delivered, updated, quarantined, released, deleted), plus the event ID that caused each one. Quarantined messages need their own addressable state, so an agent can receive metadata and a risk decision without the untrusted body attached. Block the send until that decision is stored. A body you have not accepted should not be able to start one.

Authentication Checks Before an Agent Reads Mail

Authentication runs before the body reaches the model, and it runs in that order for a reason: a model that has read an instruction cannot un-read it. NIST treats SPF, DKIM and DMARC as complementary mechanisms rather than interchangeable ones, with each check answering a different question (NIST SPF, DKIM and DMARC guidance).

A diagram illustrating the SPF, DKIM, and DMARC authentication process used before an agent reads an email.

CheckWhat a pass establishesWhat a pass does not establish
SPFThe sending server was authorized for the envelope senderThat the message content is safe or the sender intends well
DKIMA signing domain covers the message and it was not altered in transitThat the instructions in the body are harmless
DMARCThe From domain aligns with an authenticated domain and the owner's policy was appliedThat the message has no phishing or prompt-injection content
Received header chainEach relay recorded its hop in orderAnything about the sender's intent

Fields to store with every message

Keep the raw results, not a single sanitized boolean. The useful set is: SPF outcome and the envelope sender it applied to, DKIM outcome plus the signing domain, DMARC disposition and From-domain alignment, transport metadata such as TLS state, and the receiver's final action. Add a correlation ID and timestamp to each classification so a later forensic question has an answer.

The routing rule that follows

Messages that fail DMARC or show a From-domain mismatch go into a quarantine state that exposes metadata and a short sanitized preview only. The body stays out of the agent's working context until a person releases it. Low-risk messages enter the normal inbox and are processed like any other mail. How screening and quarantine interact with agent access is covered in this breakdown of AI email security, which is worth reading before wiring the release path.

A DMARC pass means the domain is who it says it is. It says nothing about whether that domain wants to attack you.

That is the whole reason the quarantine state exists. A message from an authenticated brand domain can still carry phishing, social engineering or instructions aimed at the agent, written either by the domain owner or by someone who took over an account there. NIST's guidance places authentication as one signal inside a layered pipeline that also weighs malware verdicts, sender reputation, anomalous links, attachment types, sender history and instruction-like text.

The Received chain matters after the fact. RFC 5321 requires a gateway to prepend a Received header without altering the existing ones, so preserve the full chain byte for byte. It's the only delivery trace that survives once the message is stored. Log every classification, quarantine, release and agent-access decision with a timestamp and a correlation ID, and keep the original immutable while normalized text lives in its own column.

How to Poll an Inbox with a Sync Cursor

Polling gets treated as the beginner option. It's the recovery path every push design eventually falls back to, and it's the only method whose failure is visible in a single value.

A four-step infographic illustrating how to poll an email inbox using a persistent sync cursor for integration.

  1. Store the cursor in durable storage. A database row, a persisted cache, a file on a mounted volume. Not a module-level variable: every deploy wipes memory, and every deploy then re-reads from an old position or skips forward.
  2. Request messages after that cursor. Pick a page size the run reliably finishes before its own timeout, and confirm the API returns a stable order. A page that can't complete inside the timeout is a page you'll fetch twice.
  3. Dedupe each message on Message-ID. Check the store before parsing anything. Retried pages return messages that already exist, and parsing them again is wasted tokens at best.
  4. Commit the message and the new cursor in one transaction. This is the step that makes the loop correct: a crash between two writes either duplicates a message (harmless, caught by step 3) or skips mail (silent, permanent).
  5. Route before the model reads. Apply the authentication verdicts from the previous section and write the message into normal, quarantined, updated or deleted. Quarantined messages never get their body passed to the agent.
  6. Apply changes in place. An update or a delete modifies the existing record. Creating a second record for the same Message-ID breaks threading and doubles the agent's view of one conversation.
  7. Sleep with jitter and back off on errors. A fixed interval plus random jitter keeps a fleet of agents off the same second. Exponential backoff on 429 and 5xx responses stops a retry storm from becoming the outage.

The slip sits one line above the correct code, and it survives every test: the cursor advances before the message write commits. Tests don't crash between those two calls, so the bug ships and shows up months later as a customer whose reply never got a response. If only one of the two writes can be inside the transaction, put the cursor last.

A Molted Email mailbox is read over the REST API or an MCP connection, and the seven steps above apply unchanged; the same events are also visible through the molted listen command while developing.

Verify the loop before trusting it. Take the cursor value from the start of a run, replay the same window, and confirm the second pass returns no new records. Then kill the process mid-page and check that the restart resumes from the last committed message rather than the last fetched one.

How to Process Webhooks and Live Events Safely

Push paths fail in a specific order, and the handler has to assume every delivery is at least the second copy of something. The sequence below keeps that assumption cheap.

  1. Verify the signature over the raw request body, using the scheme the provider documents, and reject any request that fails with a 4xx. Parsing JSON first and hashing the re-serialized object is the most common way this check passes everything unnoticed.
  2. Return 2xx before running agent logic. Acknowledge in milliseconds. Providers time out measured in seconds and retry on anything slower.
  3. Insert the event ID under a unique constraint and stop if the insert conflicts. The database, not the application, is what makes duplicate delivery harmless.
  4. Queue the work. A job carrying the event ID and the message ID survives a worker restart, a deploy and a model outage.
  5. Re-fetch the message by its ID. The event says something changed. It doesn't say what the message contains now, and a queued job may run after two further updates.
  6. Record the last acknowledged event ID. On reconnect or on a gap in the sequence, call the replay endpoint from that point instead of guessing how much was missed.

The failure this order prevents

Running the agent inline inside the webhook handler causes three linked failures. The model call takes longer than the provider's timeout window, so the provider retries a request that is still running, the retry starts a second agent run on the same message, and the user receives two replies that say almost the same thing. It's not an edge case. It's the default behavior of a synchronous handler holding a slow model.

When the stored record and the event disagree, trust the record and log the mismatch. The event is a hint about when to look, not a description of what's true.

Live event streams need the same discipline with one addition: reconnect using the last event ID the client processed, never the last one it received. Events held in a buffer that were never handled are still unhandled after a reconnect.

Deliveries, bounces, replies and approval decisions all arrive on the same push paths, and they don't deserve the same handler. A bounce updates the status of an address. An approval decision is a gate that was already open or closed by a person, so it should resume a queued action rather than trigger a new composition. Treating a bounce like an inbound message is how an agent ends up replying to a mailer daemon.

Webhook Handler Code Example

A webhook should be acknowledged only after its event is safely recorded and queued. This Node handler verifies the signature against the raw request bytes, uses a unique event ID to reject duplicate deliveries, then publishes the work to a queue. Mount express.raw({ type: "application/json" }) on this route so JSON parsing does not alter the bytes used for signature verification.

import { createHmac, timingSafeEqual } from "node:crypto";
import type { Request, Response } from "express";

const SECRET = process.env.INBOUND_WEBHOOK_SECRET!;

function validSignature(raw: Buffer, header: string): boolean {
  const expected = createHmac("sha256", SECRET).update(raw).digest("hex");
  const a = Buffer.from(expected, "utf8");
  const b = Buffer.from(header, "utf8");
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}

export async function inboundHook(req: Request, res: Response) {
  const raw = req.body as Buffer;              // exact bytes, not parsed JSON
  const sig = String(req.header("x-webhook-signature") ?? "");
  if (!validSignature(raw, sig)) return res.status(401).end();

  const event = JSON.parse(raw.toString("utf8"));

  try {
    await db.query(
      "insert into webhook_events (event_id, received_at) values ($1, now())",
      [event.id],
    );
  } catch (err: any) {
    if (err.code === "23505") return res.status(200).end(); // duplicate, done
    throw err;
  }

  await queue.publish("inbound-mail", {
    eventId: event.id,
    messageId: event.message.id,
  });

  return res.status(202).end();
}

Send the same signed event twice, then check that the database contains one record:

curl -sS -X POST https://example.com/hooks/inbound \
  -H "content-type: application/json" \
  -H "x-webhook-signature: $SIG" \
  --data-binary @event.json

# run the identical request a second time, then check the table
select count(*) from webhook_events where event_id = 'evt_01HX8Q';

The query should return 1.

The unique insert prevents a duplicate delivery from reaching the queue after the first event has been recorded. The handler returns 202 only after queue.publish completes. If publishing is slow or fails, the handler has not yet acknowledged the event; configure retries and make queue publication safe to repeat so a retry cannot start duplicate work.

Signature formats vary by provider. Check the provider's signing documentation before using a header name or digest, and accept both secrets during a rotation overlap so deliveries remain verifiable.

Limiting What One Inbound Email Can Trigger

A NIST presentation on agentic AI threats describes an attacker planting a prompt injection inside an organizational email thread. An assistant asked to summarize the thread instead compiled earlier emails and attachments and sent them to an external address, and the presentation names the impact zero-click data exfiltration (NIST agentic AI threat presentation). The summary a user would have read still looked ordinary.

The cause isn't a parsing bug. It's that reading and sending shared one authority, so a task that should have been read-only had a send path attached to it.

A diagram illustrating strategies to prevent security risks from malicious hidden instructions within inbound emails to assistants.

Seven controls between receipt and send

  • Separate read and send keys. Each scoped to one mailbox. An agent handling inbound screening should not hold a credential that can send.
  • Bind the recipient to the stored thread record. Look up who to answer in the database. Never take the address from text the model wrote or from the message body.
  • Set a cooldown and a send budget per thread. Two sends and a ten minute gap stops the automatic reply loop that starts when two agents answer each other.
  • Check suppression status before every send, not once at signup. United States commercial email rules are a floor here: the FTC CAN-SPAM compliance guide requires senders to honor opt-out requests within 10 business days, keep the opt-out mechanism working for at least 30 days after a message goes out, and never charge a fee or demand more than an email address to process a request.
  • Derive the outbound key from the triggering event ID. A retried run then produces the same key, and the send layer rejects the second attempt instead of mailing the same person twice.
  • Take a contact lease before the first send. Two agents working the same inbox will eventually pick the same customer. A lease on the address, with an owner and an expiry, serializes them.
  • Require approval for first contact with a new address where the potential consequences warrant it. Approval for every message isn't automatically safer: constant prompts get approved without reading, and the person rubber-stamps the one that mattered.

OWASP puts emails in the category of external data sources that can carry malicious instructions, and its guidance is to treat them as untrusted data, keep instructions and data separated, and give the agent only the permissions the task needs (OWASP prompt injection guidance).

Stop conditions that end the run

Make these deterministic checks in code, not instructions in a prompt. The agent stops and hands off when the message asks to change the recipient, asks for credentials or documents, asks for a commitment on price or legal terms, or when the thread passes a reply count set in configuration. Nothing about the run should continue past a stop.

The handoff has to be a block, not a notification. If the thread moves to a person while the agent keeps its send permission, both of them answer the same message and the sender gets two replies with different answers. Once a thread is taken, the agent's send path for that thread returns an error until it's returned.

FailureTypical causeControl
Duplicate replyWebhook redelivered and processed twiceOutbound send key derived from the event ID
Reply to the wrong addressRecipient taken from the message bodyRecipient bound to the stored thread record
Runaway loopAgent replies to automatic repliesCooldown and send budget per thread
Conflicting outreachTwo agents contact the same personContact lease before the first send
Handoff gapPerson takes over but the agent still repliesAgent sends blocked until the thread is returned

Track three numbers weekly: duplicate sends per thousand, quarantine rate, and the time between handoff and the first human reply. More rules on routing replies to a person live in this guide to how AI agents handle inbound replies.

Start Receiving Agent Email Today

Build in this order, and don't start a milestone until the test for the one before it passes.

  1. Choose the delivery method. Match the workload to the first table. Test: the method fits the runtime, and one named failure is documented as the thing being designed against.
  2. Build the identifier store and the sync cursor before any push path. Test: replaying the same window returns no new records.
  3. Add authentication routing and a quarantine state. Test: a message that fails DMARC lands in quarantine with metadata only and no body in the agent's context.
  4. Split read and send credentials, and set approvals to first contact. Test: a send to an unseen address waits instead of leaving.
  5. Replay one webhook event twice. Test: one stored record and one outbound reply.

The starting point is a mailbox the agent owns rather than an API wrapper around someone else's sending service. On Molted Email, each agent gets its own address and inbox with sending, receiving and delivery included, so there's no separate Resend, Postmark or SES account to open. Approvals are a dial: a new mailbox runs on its own, and it can be set to hold first emails to new contacts or every email for a person to approve in the dashboard.


Molted Email is built for exactly this split: an agent gets its own address and inbox, inbound mail is screened for prompt-injection attempts before it reaches the model, and every outbound message is checked against mailbox policy for duplicates, cooldowns, suppressions and sending limits. Mailboxes run autonomously by default, with approvals as an optional dial for first contact or every message. Start free at Molted Email, free for people with paid plans from $19 a month.

The Molted team