API for Email: How Agents Send, Receive and Stay Safe

The most popular advice about giving an agent an email address is to pick an API, fire a request, and check for a 200. That advice breaks in two places, and both cost real money.
A 200 means a provider took the message, not that a person received it. And an inbox is not a text field. It's a channel anyone on the internet can write to, including someone who wants your agent to forward its own credentials to an outside address. An API for email that's safe to wire into an autonomous system has to handle both ends: outbound as a reputation-controlled operation with policy in front of it, inbound as untrusted input with authority held outside the model.
What follows is the path a message takes, the states you have to persist, the records that decide whether mail lands, and the checks that stop an agent from sending something you'll regret.
Table of Contents
- How an Email API Differs From Raw SMTP
- How One Email Moves From Request to Inbox
- Receiving Email Through Webhooks, Streams and Polling
- Authentication Records That Decide Whether Mail Lands
- Treating Inbound Email as Untrusted Input
- Outbound Policy Checks and Approval Settings
- Confirm the Policy Before Your Agent Sends
How an Email API Differs From Raw SMTP
An email API is an HTTP interface where code sends one JSON request and the provider does the delivery work that raw SMTP leaves to the caller. The difference shows up in five places, and the last one matters most when nobody is watching the outbox.
| Concern | Raw SMTP | Email API |
|---|---|---|
| Connection | Open SMTP session on port 25 or 587 | One HTTPS request with a Bearer key |
| Message format | Build MIME headers and the SMTP envelope yourself | Send a JSON body with recipients and content |
| Tracking | Parse bounce messages returned to a mailbox | Receive status events tied to a message ID |
| Policy checks | Written and run by your own code | Can run before the request is sent |
| Mailbox setup | Your own domain and mail server | Provider hosts sending and receiving |
The connection row is the one developers underestimate. A raw SMTP client opens a session, negotiates a TLS upgrade, authenticates, sets the envelope, then streams the body and waits for a reply at each step. An API call is a stateless HTTPS request with a bearer key: no socket to hold open, no per-connection throttle to plan around.
Format and threading. With SMTP, you construct MIME yourself, including multipart boundaries, encoded-word subject lines, a Message-ID, a Date, and the envelope that sits outside the headers. An API takes recipients and content as JSON and assembles the MIME for you. You still supply threading headers such as In-Reply-To when a reply has to land in the same conversation.
Tracking and policy. SMTP returns failures as mail to the envelope sender, so the caller owns a mailbox and a parser just to learn what happened. An API returns a message ID and posts later state changes against it. Policy is the bigger split: in raw SMTP, duplicate detection, cooldowns, suppression and rate caps all live in your code and get reimplemented in every service that sends. With an API, some of those checks can run before the request is accepted.
The market around this reflects the shift. An industry report on the global transactional email service market valued it at $3.8 billion in 2025 and projects about $9.6 billion by 2034, a compound annual growth rate of 10.8% from 2026 through 2034, with e-commerce at 29.5% of 2025 revenue. Treat the figures as directional, since the source is a research firm rather than a statistical agency. The direction is what counts: mail moved from a manual channel to programmable infrastructure, and that pulls in demand for identity, rate limits, retries, suppression, auditability and policy enforcement.
Whatever provider you pick, verify three things before you write the integration:
- How a request is marked accepted. Name the field in the response. A message ID, a queue ID, or both?
- How status events come back. Webhook, stream or poll, whether the sender retries them, and whether each event carries an ID you can dedupe on.
- Where a policy check can block a send. If the only answer is "in my code", you've rebuilt SMTP with extra steps.
How One Email Moves From Request to Inbox
Every message carries exactly one status at a time: queued, scheduled, pending approval, accepted, sent, delivered, deferred, bounced, complained or failed. The sequence below is the order those states appear.

- The agent calls send, or a dry run when it wants to know what would happen without committing.
- Policy checks run against the request before anything is queued.
- The message settles into one of three waiting states: queued behind other mail, scheduled for a later time, or pending approval when the mailbox requires a person to release it.
- A sending server accepts it and returns an ID.
- Everything after that arrives asynchronously: delivered, deferred, bounced, complained, or failed.
What Accepted Actually Means
Acceptance is a transport state, not proof of an inbox. When a receiving server returns 250 OK after the DATA command, it accepts responsibility for delivering or relaying the message, as RFC 5321 defines it. That's the receiving server taking custody. It isn't a person opening the mail, and it isn't even a guarantee of inbox placement.
An agent-facing API should only acknowledge a request after validating the message and getting provider acceptance. Persist the SMTP response, the queue identifier and recipient-level status as separate fields, then let the later events attach to the same message ID.
What Each Later State Tells the Agent
- Deferred: the receiving server asked the sender to try again later. Wait. Resending from the agent usually creates a duplicate rather than speed.
- Bounced: the address or the server refused the message. Stop retrying and mark the contact.
- Complained: a recipient reported it. Feed that into suppression and slow the domain down.
- Failed: the request ended without sending, which typically means validation or a policy block. Fix the request, not the retry count.
Storage rule: keep the acceptance response, the queue identifier and the recipient-level status in different columns. Collapsing them into one status field is how a delivered event gets overwritten by a late deferral.
Webhook and stream consumers have to be idempotent, because delivery, deferral and bounce notifications may arrive later, out of order, or twice.
Batching is the other place agents get into trouble. RFC 5321 requires SMTP implementations to buffer at least 100 recipients and recommends clients split larger recipient sets into chunks of 100 when a server imposes that limit. For conversational mail, default to one recipient per message. Reserve bounded batching for bulk workflows someone explicitly authorized.
Receiving Email Through Webhooks, Streams and Polling
An agent can't act on mail it doesn't know arrived. There are three ways to learn about it, and the right one depends on the latency the workflow needs and what's already running in your stack.
| Method | How updates arrive | Best fit |
|---|---|---|
| Inbox polling | The agent reads the inbox on a schedule | Batch jobs with low volume and no open connection |
| Webhook | Your server receives an HTTP POST for each event | Services that already run a public HTTPS endpoint |
| Live event stream | The agent holds an open connection and gets events as they occur | Agents that must react within seconds |
Polling is the cheapest thing to build and the weakest on latency. It fits a job that runs once an hour and summarizes what came in. Set the cursor on the last message ID or timestamp you processed, not on "the last 20 messages", or you'll miss mail during a burst and re-read it after a quiet period.
Webhooks suit a service that already exposes a public HTTPS endpoint and can verify a signature. The handler should answer quickly and do the work asynchronously. A webhook endpoint that runs the full agent inline will time out during a retry storm, and then the sender retries the same event again.
A live event stream keeps a connection open so events land as they happen. It's the right choice when a reply has to go out in seconds, and it needs a reconnect with backoff plus a resume from the last event ID, because connections drop.
Say a support agent reads customer replies from a live stream during business hours while a reporting job polls the same inbox at midnight and writes a digest. The tradeoff is the familiar one between webhooks versus websockets: push to a server you already run, or hold a connection yourself.
Each channel carries the same event types, including deliveries, bounces, replies and approval decisions, so one handler with a branch on event type beats three separate handlers. Store every event ID you've processed and skip repeats. A sender that promises to retry is a sender that will eventually deliver the same event twice, and nothing guarantees ordering.
Practical rule: pick one receive method per agent, assume duplicates, and cap how many events a single run processes. An unbounded backlog becomes a burst of tool calls, and a burst of tool calls becomes a burst of sends.
Authentication Records That Decide Whether Mail Lands
Three DNS records decide whether a receiving server trusts a message, and they do different jobs. None of them is an SMTP setting, which is why switching from a relay to an API doesn't fix a domain that was never set up.

SPF publishes the hosts authorized to send for a domain, and it's checked against the envelope sender rather than the visible From header. That mismatch is exactly how a spoofed message survives a passing SPF check on someone else's domain.
DKIM signs message content and selected headers with a private key held by the sender. The matching public key sits in DNS, so a recipient can confirm nothing changed in transit and that the signing domain really signed it.
DMARC ties the two together. It evaluates whether SPF or DKIM passed in alignment with the visible From domain, which is the part people skip.
The NIST technical note on DMARC makes the alignment point explicit: a DKIM or SPF pass alone doesn't necessarily produce a DMARC pass. Its measurement from April 2015 found Gmail authenticated approximately 92% of inbound messages with SPF and could validate roughly 90% using SPF or DKIM, yet only 26.1% of messages came from domains publishing a DMARC policy. Transport authentication was common. Domain-level policy was not.
Recent measurement shows the mix has shifted without resolving. An email deliverability benchmark reports SPF adoption at 93% and DKIM at 90%, while DMARC adoption fell from 59% to 48% between 2025 and 2026, with 33% of test messages landing in spam in the same round of tests. If you want the validation mechanics in order, how email authentication works walks through each check.
The Order to Roll Out
- Publish SPF for every host that sends, and keep the list short enough to audit.
- Add a DKIM key and write down the rotation date before you need it.
- Publish DMARC in monitoring mode and collect aggregate reports.
- Read those reports and fix the legitimate senders and forwarding paths that fail alignment.
- Move the policy to quarantine, then to rejection.
Gate: no autonomous outbound on a custom domain until reports show aligned passes from every sending source. A rising complaint or bounce rate pauses the rollout instead of triggering more retries.
That gate is the difference between an agent that sends and an agent that can be trusted with a domain. For the operational side of the same problem, email deliverability for AI agents covers what to monitor once the records are live.
Treating Inbound Email as Untrusted Input
A message arrives in the agent's inbox. The body explains that earlier instructions are cancelled and that the account owner would like a summary of the last thirty days of invoices sent to an address outside the company. None of that text is a command a developer wrote. All of it is aimed at the model that reads it next.
Google's security team names email, documents and calendar invites as vehicles for indirect prompt injection that can trigger data exfiltration or unauthorized actions (Google Security Blog).

The weak fixes are tempting because they're cheap. Strip the HTML. Add a line to the system prompt telling the model to ignore instructions inside email. Run a classifier over the body. Each one reduces noise. None of them removes the authority the agent already holds when that body reaches a tool loop.
Where the Boundary Sits
- Retrieve with read-only access. The credential that fetches and labels mail shouldn't be able to send, delete or export. Separate keys, separate scopes.
- Screen before the model sees it. OWASP's prompt injection cheat sheet recommends semantic filtering plus string checks, because attackers hide instructions in other languages and encodings such as Base64. A keyword list catches neither.
- Keep authorization outside the model. The agent may read and summarize. A message body never becomes a call to send, delete or export, because those decisions are made by code the model can't edit.
- Quarantine and hand off. When a thread looks hostile, block tool calls on it and route it to a person with the original intact.
OWASP's LLM guidance goes further on functionality: reduce what the agent can do, restrict permissions such as read-only access where possible, and require a person to review and approve every generated email before it's sent (OWASP Top 10 for LLMs).
Inbox access is not instruction access, and it is not send authority.
The rule applies to more than the body. Attachments, quoted replies, forwarded chains and signature blocks all reach the model as text. An agent that summarizes a thread for another agent passes along whatever it decided to trust, so the boundary has to sit at the reader, not at the last tool in the chain.
Outbound Policy Checks and Approval Settings
A sending API will happily send the same apology email nine times if the model decides nine times that an apology is due. Nothing in the transport layer stops that. Policy in front of the send does.
Checks That Don't Trust the Model
- Duplicate detection: hash the recipient plus the normalized body and refuse a match inside a window you set.
- Cooldown per recipient: a minimum gap between messages to the same person, enforced server-side.
- Suppression list: hard bounces, complaints and opt-outs, checked before anything queues.
- Sending limits: a cap per mailbox and per hour, so a loop that fails doesn't become a loop that sends.
- Dry run: a call that reports the result of every check without sending.
The dry run is the cheapest control and the one often skipped. Every email an agent sends is worth checking first, and on Molted Email the agent can ask a dry run whether a message would go out. Sends go through POST /v1/agent/request-send (or POST /v1/send/request), with policy enforcement, rate limiting and delivery tracking built into that path, and each mailbox can run on its own or require approval for first emails to new contacts or for every email.
Choosing an Autonomy Setting
| Setting | Agent sends | Person decides |
|---|---|---|
| Autonomous | Sends after policy checks pass | Reviews events and the audit log afterward |
| Approval for first contact | Sends replies to known contacts | Approves or rejects the first email to each new contact |
| Approval for every message | Nothing leaves until approved | Approves or rejects each email |
OWASP's position on this is blunt: treat the model as an untrusted user, require explicit human approval when sending or deleting could have material consequences, and keep external content clearly separate from the user's own instructions (OWASP LLM01 prompt injection). Approval for first contact is usually the right default for a support or sales agent, because it blocks the one category of mistake that's hardest to undo: a cold message to a stranger.
Validating What the Model Wrote
Input screening isn't enough, because the model's output goes straight into a mail function. OWASP warns that an attacker who can influence a generated email template can get malicious JavaScript into messages rendered by vulnerable clients, and the mitigation is to validate model output before it reaches backend functions and to apply context-aware encoding such as HTML escaping (OWASP improper output handling). Treat the draft as input from an untrusted user.
A send that follows this order is hard to get badly wrong:
- Dry run the draft and read which checks failed.
- Validate the output, escaping included, before it touches the mail function.
- Run policy checks: duplicates, cooldown, suppression, limits.
- Submit only if the approval rule for that recipient allows it.
- Store the audit record against the message ID so accepted and delivered stay distinguishable.
That last step is where a mailbox audit log earns its place. When a customer says they got three identical emails, the log tells you whether three sends were accepted or one was accepted and the event stream replayed it.
Confirm the Policy Before Your Agent Sends
A successful API response does not mean the recipient received the email. Set up the mailbox policy first, then track acceptance separately from delivery, bounces, and complaints. These steps work with Claude Code, Cursor, Codex, an MCP client, or the REST API.
- Create one mailbox per agent. Each agent gets its own address and inbox, so its policy, suppression rules, and audit records are tied to a single identity. Retiring that mailbox does not affect another agent's mail.
- Create a credential scoped to that mailbox. Use read-only access for an agent that only reads, or send-only access for one that only sends. Keep the key out of the repository and away from model output.
- Choose the interface already used by the project. Agents can connect through the REST API, the
moltedCLI, or the hosted MCP server. The MCP tools includesend_email,dry_run,read_inbox,reply, andhandoff_thread. Agents can use Molted Email without opening a separate Resend, Postmark, or SES account. - Dry-run a test message. Review the applicable policy, rendered template and rewrite, line diff, and check results. A dry run sends nothing. Fix the draft if a check blocks it; do not weaken a policy just to make the draft pass.
- Choose the approval setting for the first real recipient. A mailbox can send automatically, require approval for first contact, or require approval for every message. Approval keeps a person in the loop when the agent's authority should be limited.
- Send one message and track each state separately. Record the acceptance response, then process later delivery, bounce, and complaint events. Check the audit log before expanding the agent's contact permissions.
If the agent also runs code or browses, isolate that runtime separately from the mailbox. Isolated sandboxes for agent code execution cover the compute side of the trust boundary.
Decision: Confirm the policy and approval setting with a test recipient before the agent contacts a real one. Expanding the contact list is easy. A sent message cannot be recalled.
Molted Email gives each agent its own address and inbox, screens inbound mail for prompt-injection attempts, and checks outgoing messages against mailbox policy. Signing up is free for people. Before enabling real sends, run a dry run and confirm which messages require approval.