Programmatic email for agents: the webhook-to-agent loop
Programmatic email for agents requires one stateful pipeline that handles inbound webhooks, deduplication, and draft states together. This article walks through the full loop: webhook payload structure, idempotent processing, draft approval patterns, and failure modes you can implement today.
On this page
TL;DR: Build a reliable agent email loop by treating inbound webhook delivery, idempotent processing, and draft-then-send reply states as one stateful pipeline rather than three separate integrations. The webhook must deliver full message body and attachments (not metadata only), your handler must deduplicate on message ID before processing, and high-risk replies should flow through a draft state with explicit approval. Draft-then-send adds latency, so reserve it for high-risk sends and let low-risk replies go out automatically. Also note that an instant agent mailbox is receive-only until you connect it to a workspace. Set a turn budget before triggering human review.
Your agent can both send and receive email, but the hard part is making those two operations share one state machine.
Most email platforms integrate inbound and outbound in one product. Mailgun offers inbound routing natively alongside sending through its Inbound Routes feature, and it has an MCP server with 50+ tools, but it has no agent inbox primitive. SendGrid bundles transactional sending and inbound parse in the same account, and its published MCP server also has 50+ tools, with no agent inbox primitive. Postmark supports inbound email through an MX record or a generated @inbound.postmarkapp.com address, and its official MCP server exposes 24 tools covering sending, templates, message search, delivery diagnostics, bounces, suppressions, and webhooks, but no per-agent inbox primitive is documented.
Having inbound and outbound in one account does not give your agent its own mailbox. Your agent still treats inbound and outbound as one conversation. An arriving email carries the sender, subject, message ID, and prior thread, and your agent's reply needs to thread headers, suppress duplicates, track state, and handle failures without human intervention.
This article shows the full inbound-to-outbound loop: inbound webhook fires, agent reads and threads the message, agent drafts or sends a reply, and agent handles forwarding and attachments. Low-risk replies can run fully automated, while high-risk replies route through human draft approval. The sections below walk through event payload structure, idempotency handling, draft-then-send patterns for high-risk replies, and the failure modes each stage can hit.
Closing the loop: from webhook to agent response
Programmatic email for agents requires more than an API that can send and receive. It requires a stateful pipeline where inbound webhooks carry enough data for your agent to act, your handler deduplicates at-least-once deliveries, and replies flow through draft states when the risk of a wrong send is high.
The loop starts when an email arrives at your agent's inbox. Your email provider parses the message and fires a webhook to your endpoint with the full message body, headers, and attachments. Your webhook handler extracts the fields your agent needs, checks if you've already processed this message, and routes it to the agent loop. The agent reads the message, retrieves prior conversation state, decides whether to reply immediately or draft for review, and sends or saves the response. Thread state updates so the next message in the conversation has full context.
Architecting for asynchronous loops
Email is inherently asynchronous. Your agent cannot block waiting for a reply. When an inbound webhook arrives, the agent must retrieve prior session state, process the new message in context, and update state for the next turn. Your session state should carry conversation history, turn count, accumulated token usage, and any draft replies awaiting approval.
Unlike a synchronous API call where the client waits for a response, email moves over SMTP, the mail transport protocol defined in RFC 5321, which supports a store-and-forward delivery pattern rather than direct end-to-end delivery. A message arrives, your agent processes it, and the reply goes out. Minutes or hours later, another message arrives in the same thread. Your agent must resume from saved state, not from scratch.
Breaking down the email loop lifecycle
The lifecycle has six stages:
- Receive: Inbound email arrives at your mailbox and triggers a webhook
- Parse: Your handler extracts message ID, thread ID, sender, body, headers, and attachments
- Thread: Retrieve prior conversation state and add the new message to history
- Decide: Agent determines whether to reply, forward, escalate, or archive
- Draft or send: High-risk replies save as drafts, and low-risk replies send immediately
- Observe: Update thread state, increment turn counter, log token usage
Each stage has failure modes. Webhooks can fail to deliver. Different MIME parsers can also extract different results from the same malformed or ambiguous message, according to an IETF Internet-Draft, so your handler can misread bodies or attachments on malformed MIME. Thread state can be stale. The agent can loop without terminating. Replies can send to the wrong address. The sections below cover the failure modes that matter most for agent loops.
Syncing email state for AI agents
Thread state maps to agent state through three key fields: message_id (stable across retries), thread_id (groups messages in a conversation), and headers (In-Reply-To and References for threading). When a reply arrives, fetch the session by thread_id, add the new message to conversation history, and resume the agent loop from where it left off.
Persistent state across sessions is fragile. If your agent crashes mid-turn or the session times out, you need to recover from saved state, not restart the conversation. Store conversation history, turn count, and token usage in a database keyed by thread_id. When a new message arrives, load the session, increment the turn counter, and continue.
How inbound email reaches your agent
How do you route inbound agent email into an AI workflow? Point your domain's MX record at your email provider's inbound servers. When email arrives, the provider parses the message and fires a webhook to your endpoint with the full message body, headers, and attachments. Your webhook handler extracts the fields your agent needs and routes the message to the agent loop.
Inbound routing delivers parsed emails with separate fields for headers, body content (plain text and HTML), and attachments, not just metadata. Resend's inbound implementation delivers metadata only, which means your agent can't read the reply body without a separate parsing layer. The webhook is the trigger for your agent loop. When it fires, your handler must return a 200 OK before the provider's timeout or the provider retries the delivery, and those timeout windows vary. Shopify documents a 1-second connection timeout and a 5-second timeout for the entire request, per its webhooks documentation. GitHub fails a delivery after 10 seconds, while the Standard Webhooks spec recommends producers wait 15 to 30 seconds. Check your own provider's documentation for its current limit.
Key fields in agent webhook data
The minimum set your agent needs to respond coherently:
Note: Field names and types in this table are typical examples, not a documented send.io payload schema. Verify each one against the payload your endpoint actually receives before relying on it.
Field | Typical type | Example | Why it matters |
|---|---|---|---|
| String |
| Stable deduplication key across retries (RFC 5322) |
| String |
| Groups messages in a conversation without rebuilding the reference chain |
| Array of objects or a single object (varies by provider) |
| Sender address. Check whether your provider sends an array or one object, then set your reply's |
| Array |
| The mailboxes that received the message, which routes to the right agent |
| String |
| Decoded from RFC 2047 encoded-words, not raw |
| String | Full plain-text body | Decoded, charset-converted. What your LLM reads |
| String | Full HTML body (if present) | Alternative representation. Parse if needed for formatting |
| Object |
| Threading context. Use |
| Array |
| Metadata for files. Content is usually fetched on demand via URL |
Webhook providers should include a unique event ID that stays constant across retries, according to one guide on webhook reliability patterns. Use message_id as your deduplication key.
Extracting inbound email data fields
A webhook handler in Node.js parsing the payload:
// Your endpoint receives a POST from send.io
app.post("/webhook/inbound-email", async (req, res) => {
const payload = req.body;
// Extract fields needed for the agent loop
const {
message_id, // Idempotency key
thread_id, // Session correlator
from, // Sender address (your reply's recipient)
to, // Which agent mailbox received it
subject, // Already decoded
text, // Plain text for the LLM (string)
html, // HTML if you need it (string)
headers, // In-Reply-To, References, etc.
attachments // Attachment array (format varies by provider)
} = payload;
// Record receipt time locally; payload timestamp field names vary by provider
const receivedAt = new Date().toISOString();
// Check whether this message was already processed
const processed = await db.query(
"SELECT 1 FROM processed_emails WHERE message_id = ?",
[message_id]
);
if (processed.length > 0) {
return res.status(200).send({ status: "already_processed" });
}
// Record it immediately (before async work) so a retry sees it
await db.query(
"INSERT INTO processed_emails (message_id, received_at) VALUES (?, ?)",
[message_id, receivedAt]
);
// Now route to the agent
const agentReply = await runAgentLoop({
mailbox: to,
sender: from,
subject,
body: text,
threadId: thread_id,
messageId: message_id,
headers,
attachments
});
res.status(200).send({ status: "queued", reply_id: agentReply.id });
});
The send.io API documentation covers the full webhook payload structure, including delivery events, bounce diagnostics, and complaint handling.
Linking inbound emails to agent sessions
Each message carries a thread_id. Use this to restore the agent's session state: prior messages in the conversation, context about what the user asked, and any draft replies the agent was working on. When a reply arrives, fetch the session, add the new message to the conversation history, and resume the agent loop from where it left off.
Session state should include turn count and accumulated token usage, so you can halt before the agent reaches its budget. A budget sets the most an agent, team, or feature may spend over a period, in dollars or tokens, according to AI agent governance patterns.
Managing file attachments via webhooks
Attachment delivery format varies by provider: some embed Base64-encoded content directly in the webhook payload, while others send metadata plus a URL. Check which model your provider uses before writing the handler. In the URL model, which the example below assumes, the webhook payload contains an attachment array where each item includes the filename, MIME type, file size, and a time-limited presigned URL pointing to the binary stored on the platform's object storage. Download attachments on demand, not in the webhook handler, but when the agent needs to read them.
// When agent needs to read an attachment
const attachment = payload.attachments[0];
const response = await fetch(attachment.url);
const buffer = await response.buffer();
// Pass to your document parser (pdf, csv, etc.)
Store URLs in your database. Fetch content only when the agent needs to parse the file. This saves bandwidth and storage.
Ensuring delivery with idempotent email processing
At-least-once delivery means a provider promises to deliver every event one or more times, but never promises to deliver it exactly once. Your webhook handler will see the same message more than once. Build for that from day one.
Because the network can drop the acknowledgement, no provider can promise exactly-once delivery over plain HTTP. What they offer is at-least-once: the event is delivered one or more times, and it's your job to make repeats harmless, as explained in webhook retry and idempotency patterns.
Handling at-least-once webhook delivery
The pattern is straightforward:
- Receive the webhook
- Check if
message_idexists in a processed-emails table - If it does, return 200 OK and stop (idempotent)
- If not, insert the
message_idin the same transaction as your side effect (routing to the agent) - Process the email
Record it the moment you accept the delivery, inside the same transaction as the side effect, with a unique constraint.
Enforcing unique keys for agent webhooks
Use message_id (the RFC 5322 Message-ID header) as your deduplication key. It's stable across retries and globally unique.
// Atomically insert or return early
try {
await db.query(
"INSERT INTO processed_emails (message_id) VALUES (?)",
[message_id]
);
// First delivery; process it
await processEmail(payload);
} catch (err) {
if (err.code === "UNIQUE_CONSTRAINT_VIOLATION") {
// Already processed; return success
return res.status(200).send({ status: "already_processed" });
}
throw err;
}
An idempotency key turns an "at least once" delivery into an "exactly once" effect. The send.io API documentation covers idempotency key behavior for outbound sends, where the caller sets a client-generated Idempotency-Key header on each request.
Preventing duplicate email processing
If your deduplication fails and the same message is processed twice, your agent will send two replies, one right after the other. This wastes tokens, sends the recipient a duplicate message, and can confuse your agent if one reply triggers a reply-to-reply. Test your dedup transaction atomicity in a staging environment before production.
Duplicate processing also wastes inference budget. If your agent processes a 10-turn conversation twice, you've doubled your token spend for that session. Set a unique constraint on message_id and handle the constraint violation gracefully.
Implementing safe reply loops with draft states
A reply loop changes state with every send, and a wrong send can't be unsent. If your agent sends a financial update, a cancellation confirmation, or a redirect to an external system without a human seeing it first, the mistake reaches the recipient immediately. Draft-then-send is your safety valve.
Automating drafts for high-risk replies
When should you draft instead of sending immediately?
- Sending to an external email address (not the original sender)
- Financial data: pricing, invoices, account changes
- Sensitive data: secrets, PII, compliance info
Drafts live in a database or object storage. They carry the recipient, subject, body, and threading headers (Message-ID, In-Reply-To, References) so an approved reply can send into the right thread. A human can review and approve, modify and send, or delete.
// High-risk reply pattern
if (isHighRisk(agentReply)) {
const draft = await saveReplyDraft({
message_id: inbound.message_id,
thread_id: inbound.thread_id,
from_mailbox: inbound.to,
to: agentReply.recipient,
subject: agentReply.subject,
body_text: agentReply.body,
threading_headers: {
in_reply_to: inbound.message_id,
references: inbound.headers.references
},
risk_reason: agentReply.riskReason,
created_at: new Date()
});
return { status: "drafted", draft_id: draft.id };
} else {
// Low-risk; send immediately
const sent = await sendEmail(agentReply);
return { status: "sent", message_id: sent.id };
}
The send.io agent mailbox documentation covers scoped API keys and permission lists for agent inboxes, so you can provision a mailbox with read and reply permissions without exposing your primary account credentials.
Managing high-risk reply intercepts
A human reviews the draft dashboard and decides: approve, edit-then-send, or delete. If approved, the reply sends with the threading headers intact. If edited, record who changed what (for audit). If deleted, log why and don't retry.
Policy checks before send can also catch mistakes. Run the reply through a content filter (no PII, no secrets, no unapproved external links) before sending. If the filter fails, draft the reply and alert the agent owner.
Preventing runaway agent email loops
A budget sets the most an agent, team, or feature may spend over a period, in dollars or tokens, according to AI agent governance patterns. Rate limits cap requests and tokens per minute for an agent, which turns a runaway loop into a slow one that someone has time to notice.
An agent budget should define stopping criteria for iterations, token counts, and dollar limits that force the loop to terminate, as covered in Augment Code's AI agent token spend analysis. Set a turn budget before triggering human review, and tune it to your workflow, because published defaults vary: the OpenAI Agents SDK defaults to a max_turns of 10, per its running agents documentation. The examples in this article use 25 as an illustrative starting value, not a documented standard. When a reply arrives, increment the turn counter. If it reaches the budget, halt the loop, save the conversation, and alert the agent owner.
Unlike a cost alert, which fires after spend occurs, a turn and token check runs before each agent turn, so your handler can halt the loop before the next model call.
Automating agent replies and thread transitions
Once the agent has decided to reply, it needs to send the email with proper threading headers, attachments (if any), and state updates.
Mapping email fields to agent state
Your agent context should include:
{
"mailbox": "support@yourdomain.com",
"thread_id": "thread_42",
"message_id": "<abc@mail.example.com>",
"in_reply_to": "<abc@mail.example.com>",
"references": "<abc@mail.example.com>",
"from_human": ["user@example.com"],
"subject": "Re: Invoice #1234",
"turn": 1,
"turn_budget": 25,
"token_limit": 10000,
"conversation_history": [
{"role": "user", "content": "Can you..."},
{"role": "assistant", "content": "I'll help..."}
]
}
The send.io MCP server exposes email tools directly to compatible assistants like Claude and Cursor, so you can send, receive, and manage email without building custom adapters for each project.
Maintaining thread state for agent loops
When your agent replies, set the threading headers:
In-Reply-To: Themessage_idof the message you're replying toReferences: The full chain of message IDs in the thread
const reply = {
to: agentReply.recipient,
from: inbound.to, // The mailbox that received it
subject: `Re: ${inbound.subject}`,
body: agentReply.body,
headers: {
"In-Reply-To": inbound.message_id,
"References": inbound.headers.references || inbound.message_id,
"X-Agent-Session": sessionId,
"X-Turn": turnCount
}
};
Sending a new message or forwarding starts a new thread, while a reply sets the threading headers and unarchives the thread, as described in the agent mailbox documentation. An instant agent mailbox created without an account is receive-only. To send or reply, connect it to a workspace. Once connected, that mailbox can send up to 50 emails a day from the workspace's credits. This limit applies to instant agent mailboxes only. Sending limits for other mailbox types, including mailboxes provisioned through the agent inbox API, are not covered in this article. Check the agent mailbox documentation for current limits.
Configuring external email redirection
If the agent needs to forward the message to a human or escalate to a different system, forward it to the external address with the original thread intact:
if (agentReply.action === "forward") {
await forwardEmail({
original_message_id: inbound.message_id,
to: agentReply.forward_to,
note: agentReply.forward_note,
preserve_headers: true // Keep In-Reply-To and References
});
}
Forwarding starts a new thread: the forwarded message includes the prior exchanges in its body, but the threading headers (In-Reply-To and References) do not survive the forward, so the recipient's mail client files it as a new conversation. If keeping one thread matters, reply within the existing thread instead, because replies preserve the In-Reply-To and References headers that hold the conversation together.
Configuring attachments for email APIs
If your agent generated a file (a report, a CSV, a PDF), attach it:
const sent = await sendEmail({
to: reply.to,
from: reply.from,
subject: reply.subject,
body_text: reply.body,
headers: reply.headers,
attachments: [
{
filename: "report.pdf",
content_type: "application/pdf",
content: pdfBuffer // or a URL for the platform to download
}
]
});
The send.io API documentation covers attachment handling for outbound sends, including size limits and content type validation.
Debugging edge cases in agent email loops
Common failure modes and how to diagnose them.
Diagnosing inbound webhook delivery gaps
If a message doesn't arrive:
- Check the webhook logs in your platform dashboard (timestamps, payloads, response codes)
- Verify your endpoint returns 200 OK within your provider's timeout window (timeouts vary by provider, as covered earlier)
- Look for DNS failures on your domain's MX records (use
nslookupordig) - Confirm your webhook endpoint serves HTTPS with a valid certificate
The non-negotiable baseline is RFC 5321 (SMTP transport), RFC 5322 (message format), RFC 7208 (SPF), RFC 6376 (DKIM), and RFC 7489 (DMARC). If your domain's SPF or DKIM records are misconfigured, inbound email may not reach your mailbox.
Configuring email delivery retries
A devlume.com webhook reliability guide reports that AWS research found full jitter cut peak retry load by roughly three quarters compared with no jitter. Use exponential backoff that doubles the wait between attempts, typically starting at 1 second and growing through 2, 4, 8, and 16 seconds, with a cap near 30 seconds, per Vercel's exponential backoff reference. Add jitter (a small random offset on each wait, such as ±10% as an illustrative value) to avoid thundering herd. When your retry budget is exhausted, move the message to a dead-letter queue and alert. Set the attempt count per system.
Metrics for programmatic email flow
Monitor these in production:
- Webhook delivery rate: % of inbound messages delivered to your endpoint within your SLA window (set the window from your own handler timeout and requirements)
- Webhook latency: Time from send to webhook arrival (set a target from your own measured baseline)
- Dedup hit rate: % of webhooks that match a prior
message_id(some baseline is expected from provider retries, and a sustained rise points to handler timeouts) - Turn budget consumption: Average turns per session (track for runaway loops)
- Agent error rate: % of sessions where the agent crashes or hits a timeout
Implementing session turn budgets
// Before agent runs
if (session.turn >= session.turn_budget) {
await escalateToHuman({
reason: "Turn budget exhausted",
turn_count: session.turn,
tokens_used: session.tokens_used
});
return { status: "escalated" };
}
// After agent completes a turn
session.turn += 1;
session.tokens_used += response.usage.total_tokens;
if (session.turn >= session.turn_budget) {
// Log for review
console.warn(`Session ${sessionId} reached turn budget`);
}
This check runs before each agent turn and escalates to a human when the turn counter reaches turn_budget. The turn_budget value of 25 in the example is the illustrative figure from the runaway loops section above.
Next steps
Provision an agent inbox and test the inbound routing behavior in the sandbox. Create a scoped mailbox, send test emails to it, and verify your webhook handler deduplicates and routes correctly before moving to production.
FAQs
Can an agent reply to every inbound email automatically?
Yes, for low-risk replies. Draft high-risk replies (external recipients, financial data, sensitive data) so a human checks the most consequential sends. Set a turn budget and monitor token usage.
What happens if two emails with the same message ID arrive at the same time?
Use a database constraint or atomic transaction on the dedup check. The first one wins, and the second gets a 200 OK and skips processing.
How long should teams keep the processed-emails table?
Long enough to outlast your provider's documented retry window. Check that window in your provider's documentation, because it differs across providers. After the window passes, a retry of the same message_id would no longer be caught. Archive old records to cold storage.
Should teams store attachment content or just the URLs?
Store URLs. Download on demand when the agent needs to read the file.
How do you test the webhook handler without real email?
Provision a test agent inbox, send test emails to it, and point its webhook at your local endpoint (via ngrok or similar). send.io's CLI can also forward signed test webhook events to a local endpoint. Verify your handler returns 200 OK and processes the message correctly.
Key terms glossary
Webhook payload: The JSON object your webhook endpoint receives, containing message metadata, body, headers, and attachments. Webhooks are at-least-once delivery systems, so idempotency is the consumer's job.
At-least-once delivery: A guarantee that every event arrives one or more times. Build your handler to deduplicate.
Idempotency key: A stable, unique identifier (usually the message ID) that your handler uses to skip duplicate processing.
Thread state: The context your agent needs to understand a conversation: prior messages, the subject, the sender, and threading headers (In-Reply-To, References). Store this per session so the agent can resume coherently.
Turn budget: A hard limit on the number of agent reasoning steps per session. Tune the value to your workflow to catch runaway loops. The examples in this article use 25 as an illustrative value.
Draft-then-send: A reply pattern where high-risk emails are saved to a draft state for human review before sending. Requires a webhook to notify your agent that the reply was approved.
MX record: A DNS entry that directs inbound email for your domain to your email provider's inbound servers. Point it at send.io's servers to route mail through the platform. Configure it once per domain, and all email at that domain follows that route.