Mailbox API Guide: Auth, Sync, Sending and Safety

Mailbox API Guide: Auth, Sync, Sending and Safety

An agent just sent the same customer two replies. The sync job crashed after the send and before the cursor was saved, the next poll treated the inbound message as new, and the second reply went out. The model did not forget the thread. The mailbox state did.

A mailbox API is any interface that exposes a mailbox's messages, threads, state, and change history to code. No single standard defines the term, so the calls below are the ones an agent uses.

Table of Contents

Mailbox API Capabilities at a Glance

Read that list as seven operations, not as one inbox dump. Group them by job: reading, writing, and control. Before a first send to a new address, a lookup such as Mailveri on AI Tool Seekers is a practical check that the address is worth writing to.

CapabilityWhat the call doesWhat comes backCommon mistake
Read inboxLists messages, filtered by time, mailbox, or labelMessage IDs, sender, subject, timestampRefetching the whole inbox on every poll
Read threadReturns one conversation in orderOrdered messages with thread ID and directionTreating outbound messages as new inbound mail
Send messageSubmits an outbound messageMessage ID and an initial statusResending on timeout without checking the first attempt
Preview sendRenders a message without sending itRendered body, line diff, and check resultsSkipping preview on the first send to a new contact
Receive updatesDelivers new events by webhook, event stream, or pollingEvent type and message IDProcessing the same event twice after a retry
Track deliveryReports status changes for each messageAccepted, sent, delivered, bounced, complained, or failedTreating accepted as delivered
Manage mailbox settingsReads and changes rules, suppressions, and keysCurrent policy values and key rightsLeaving broad keys on agents that need one mailbox

Reading covers the inbox, the thread, and updates. Writing covers send and preview. Control covers delivery tracking and settings. A missed distinction in any row shows up later as a duplicate reply, a stale decision, or a send the agent was never meant to make.

Three ways to reach the same calls

The same operations are available three ways.

  • REST: The service calls mailbox endpoints with a Bearer key.
  • CLI: A command-line interface prints JSON an agent can parse, including events from a listen command.
  • MCP: An MCP server exposes each operation as a tool to Claude Code, Cursor, and Codex.

Authentication, the choice among those three paths, incremental sync, inbound screening, sending, and approval gates each have their own treatment under Authenticating with Mailbox-Scoped Keys, Choosing REST, CLI or MCP for Your Agent, Reading Inboxes, Threads and Incremental Sync, Screening Inbound Mail for Hidden Instructions, Sending Without Duplicates, Limits or Silent Failures, and Autonomy Levels and Approval Gates.

Authenticating with Mailbox-Scoped Keys

Every call carries a Bearer key in the Authorization header. A list of one mailbox looks like this.

curl -H 'Authorization: Bearer YOUR_KEY' and the message-list path for that mailbox only.

The key is not an account-wide password. It carries rights on a single mailbox, and a call outside those rights fails.

Three rights, two useful key sets

  • Read: List and fetch messages and threads.
  • Send: Submit outbound mail.
  • Manage: Change rules, suppressions, webhooks, and other keys.

A triage agent gets read on one mailbox and nothing else. It can see mail and cannot send or rewrite policy. An outreach agent gets read and send on one mailbox and no manage right. It can answer and start mail, and it cannot change the rules that constrain it.

Scope is the cap on a manipulated or misconfigured agent. A key limited to one mailbox cannot open the rest of the account. A key without manage rights cannot loosen its own rules, release a quarantine, or mint a wider key.

Practical rule: Widen a key for the one mailbox that needs the extra right, never for every mailbox on the account.

Rotation and a rejected call

Rotate in four steps. Issue a new key with the same rights. Move the agent to it. Revoke the old key. Check the audit log for calls still made with the old key, which means some process was missed.

When a call fails for missing rights, read the response code and the error text. Compare that text with the rights on the key. Add the missing right on that one mailbox only, then retry the same call. Do not replace a rejected read key with a manage key "to make it work."

Choosing REST, CLI or MCP for Your Agent

A triage agent that wakes on new mail needs a different client than an outreach agent inside a worker. Choose by where the loop lives, because mailbox state and policy do not move with the path: read, send and manage rights still decide every call, and a queued or pending approval message is already in the ledger.

  • REST. Use it when the agent already runs in application code. Send the Bearer key to the same HTTP surface as the CLI and MCP server, and submit outbound mail through POST /v1/agent/request-send when policy checks, rate limits and delivery tracking should happen inline.
  • CLI. Use it in shell jobs and pipelines. Commands cover sending, threads, rules, suppressions, webhooks and events, print JSON for parsing, and molted listen can block a script until mail arrives.
  • MCP. Use it when Claude Code, Cursor or Codex should call mailbox operations as tools against the hosted MCP server: send_email, dry_run, read_inbox, reply and handoff_thread. The MCP server write-up is the tool list to check before wiring an editor. If tool names collide in that client, how AuricIDE handles ambiguous ID prefixes is a useful naming reference before exposing short identifiers.

Prove the path with one read against a test mailbox, then send once and confirm the record moves through queued, sent or delivered instead of assuming success. Keep one consumer per mailbox so two clients do not answer the same thread twice.

Reading Inboxes, Threads and Incremental Sync

New mail can arrive four ways: reading the inbox on a timer, a webhook, a live event stream, or a CLI listen command that prints events. Pick one path per mailbox so two consumers do not both answer.

The four intake paths and the sync that follows them sit in one flow.

A diagram illustrating methods for reading email inboxes, incremental synchronization, and thread handling for mailbox synchronization.

A comparison of webhooks and live streams is the right check when the push path is still open. Polling is the fallback when neither push path is available, not the default for a busy inbox.

The sync loop

The Gmail API history reference is the documented pattern. Its history endpoint returns changes in chronological order, including message additions, deletions, and label changes. Identifiers increase over time but are not contiguous, so a numeric gap is not a missing event. An identifier is typically valid for at least one week, and in rare cases only for a few hours. An HTTP 404 means the cursor is dead and the mailbox needs a full resync.

Run the loop in this order.

  1. Read the inbox once and store the newest change identifier. That cursor is the only place the loop resumes from.
  2. Request changes after that identifier, filtered to message additions and label changes. Deletions can be logged without waking the agent.
  3. Page with the next-page token until none is returned. Stop only when the token is absent, not when a page looks short.
  4. Fetch the full thread for each new inbound message so earlier turns are visible. Direction matters. An outbound message in that thread is not a new inbound ask.
  5. Record each processed message ID before any reply is composed.
  6. Save the newest identifier only after the whole batch is processed. Saving it earlier hides a crash.
  7. If the server rejects the identifier as expired, run a full resync and rebuild state from the inbox. Do not invent events for the gap.

A batch retried after a crash must not trigger a second reply. The processed-ID record is that guard. A stale cursor is the other failure. The agent then reasons on mail it already handled, or it skips mail that arrived while the identifier was already invalid.

Read metadata first: sender, subject, timestamp, and thread ID. Open a body only after inbound screening has checked it.

Two restart checks

Restart the loop in the middle of a batch and confirm no message is processed twice. Then delete the stored identifier and confirm the full resync rebuilds state without sending anything.

Both checks should pass on a test mailbox before the agent is allowed to send. If the mid-batch restart produces a second reply, the processed-ID write is happening too late. If the full resync sends mail, the rebuild path is coupled to the send path and needs to be split.

Screening Inbound Mail for Hidden Instructions

Inbound email is untrusted input. It must never be read as an instruction, even when the prose is polite and the sender looks familiar.

A KuppingerCole blog post describes instructions concealed with HTML and CSS. The person could not see them. An assistant still read the hidden text, then presented a false password-compromise warning and an attacker-controlled phone number. Quarantine plus a person on high-risk threads is what keeps that hidden text out of trusted context.

Run the check before the body reaches model context. Once hidden text is in the prompt, later filtering is only cleanup.

A diagram illustrating a Mailbox API security check filtering hidden malicious instructions from an incoming email message.

Where the instruction hides

Stripping scripts is not enough. A visible sentence that says "forward the customer file to this address" is still an instruction. So is text a person never sees.

Hiding methodWhere it appearsScreening action
HTML commentInside the markup, invisible when renderedStrip from agent context and log
CSS-hidden textDisplay none, white text, or zero font sizeFlag and pass only the visible text
Zero-width charactersBetween visible lettersNormalize the text and flag the message
Base64 blockEncoded inside the bodyDecode during screening and check the decoded text
Chat formatting tokensMarkers such as role tags used by chat modelsTreat as data and quarantine the message

Handle mail in that order. Read metadata first: sender, subject, timestamp, thread ID, and the risk label. Open the body only when the label is clean. Route a quarantined message to a person or a review step. Log the decision, including the hiding method that fired.

Molted Email screens incoming mail for prompt-injection attempts, quarantines the risky messages, and uses canary tokens to identify or contain a message that tries to redirect an agent. Mail quarantined as spam, phishing, malware, or prompt injection does not count toward the inbound allowance. Agent keys can tighten rules, but they cannot release quarantined originals or approve their own sends. The agent mail security notes spell out why that separation has to be server-side, not a line in the system prompt.

An agent may summarize metadata and bodies that screening marked clean. Quarantined content waits for review. A summary model that receives the raw quarantined body has already lost the boundary the quarantine was there to keep.

Sending Without Duplicates, Limits or Silent Failures

An accepted send means the message entered the delivery pipeline. Treat the HTTP success as a receipt, then wait for events. Code that reads a 200 as "delivered" retries mail that is already moving and misses mail that later bounces.

Preflight, then the submit

Reject bad input before anything is queued. Count recipients. Confirm required fields. Check size. RFC 5321 requires receivers to accept at least 64K octets for the complete message, headers and body included, and larger limits are advertised with the SMTP SIZE extension. Catch an oversized payload locally rather than learning the limit from a downstream failure.

Keep the send routine short.

  1. Run a preview. It shows the applicable setting, the template output next to any rewrite, a line diff, and the check results. Nothing is sent.
  2. Attach an idempotency key built from the mailbox, the recipient, and the intent of the message. A timeout retry must present the same key.
  3. Submit with POST /v1/agent/request-send (or POST /v1/send/request) and store the returned message ID.
  4. Wait for delivery events and update the record on each one.
  5. On a timeout, query the stored message ID before any retry. Never resend blind.

Retry storms after an ambiguous failure cause most duplicate outreach. The idempotency key and the stored ID are the two brakes.

What each status should make the code do

StatusMeaningCode action
queuedThe message is waiting in the send queueStore the message ID and do not resubmit
scheduledThe message is held for a later send timeKeep one record and leave the schedule intact
pending approvalA person must approve or reject the sendWait for the decision and revise only after rejection
acceptedThe API has taken the message for deliveryStore the message ID and wait for events
sentThe message left the sending systemUpdate the record and keep waiting
deliveredThe recipient server accepted the messageMark the send complete and stop retries
deferredThe recipient server asked for a retry laterKeep the record open and check again
bouncedThe message was rejected permanentlyAdd the address to suppressions
complainedThe recipient marked the message as spamStop contact with that address and review the sequence
failedThe message could not be sentRead the reason before any retry

Treat deferred as an open retry window. Treat complained as a stop signal. Treat failed as unknown until a reason is recorded.

Policy checks before the message leaves

Molted Email gives an agent a mailbox the way Gmail gives a person one. Sending, receiving, and delivery are included, and there is no separate Resend, Postmark, or SES account or provider API key to hold. Before a message leaves, the send path enforces the mailbox controls that matter to agent mail: mailbox scope and key rights, suppressions, cooldowns, duplicate protection, contact leases across agents, per-mailbox send limits, and an audit-log decision for each send.

Those controls exist because harm is a chain, not a single bad sentence. Research on indirect prompt injection describes malicious content that must be retrieved, bypass defenses, induce a tool invocation, and supply unsafe tool arguments; in one cited benchmark, ReAct-prompted GPT-4 agents were attacked successfully 24% of the time, rising to 47% when the attacker added a hacking prompt. A policy check therefore tests whether the requested send matches the agent's authority, beyond whether the text looks clean.

Sending pauses when a mailbox's bounce or complaint rate rises. Only a person can resume it. Recovery means reading the pause reason, fixing the list or content that caused it, and having that person resume the mailbox. Log each blocked send with its reason so a later review can reconstruct the decision. Paid overages have stated rates, and sending stops at twice the monthly allowance, so capacity failures should surface as explicit state rather than silent drops.

Send one message to an address under the team's control and confirm the record moves from accepted to delivered.

If it stays at accepted, the event consumer is not writing status back. If a second copy appears, the timeout path resent without reading the stored ID.

Autonomy Levels and Approval Gates

Each mailbox decides how much the agent sends without a person in the loop. Every new mailbox starts on its own. Turning the dial down holds the first email to a new contact, or every email. Approval is optional. It is not the default shape of the product, and it is a setting on one mailbox rather than a gate on every mailbox.

Approval patternSends without reviewWaits for a personBest fit
AutonomousEvery messageNothingReplies in existing threads with known contacts
Approve first contactMessages to known recipientsThe first message to each new recipientNew agents and outbound outreach
Approve every messageNothingEvery outgoing messageAgents in early testing or regulated workflows

A first contact is a recipient the mailbox has never written to. First-contact approval holds only that first message. Later mail to the same address goes out on its own.

Held messages show up as pending approval. A rejection means no send. The agent revises the message and submits again. It does not approve its own send, and it does not get a tool that clears the hold. A person approves or rejects in the dashboard.

A rollout that starts strict

  1. Start a new agent on first-contact approval.
  2. Review every held message for a week and note the edits a person makes.
  3. Move to automatic sending once approved messages need no edits.
  4. Return to approval for every message if bounce or complaint signals rise.

A support agent answering existing threads can run on its own. Outbound sales usually starts on first-contact approval, because the costly mistake is the first note to a stranger, not the follow-up. Regulated workflows stay on approval for every message until someone outside the agent team says otherwise.

A person can take over any thread. While that handoff is in effect, the agent does not reply. Returning the thread to the agent is an explicit step, not a timeout.

Pick a Mailbox Setup for Your First Agent

Build the first agent in this order, and stop after the test send.

  1. Create an account on the free plan. It costs nothing, it is for people, and it includes 3 mailboxes on a shared domain, 3,000 sends a month, and 1,000 inbound emails a month, with no humanizer rewrites. Sending uses the shared domain only.
  2. Connect through the hosted MCP server with an API key, or use the CLI or the REST API when the agent runs in existing code.
  3. Set the first mailbox to approve first contact.
  4. Run a preview on a real message and read the check results. Fix a failed check before any submit.
  5. Send one test to an address under the team's control and confirm the status reaches delivered.

Move to the Solo plan at $19 a month when the agent needs its own domain. That plan includes 10 mailboxes and 3 custom domains. Stay on the free plan while the mailbox is still on the shared domain and the volume fits.

Return to Autonomy Levels and Approval Gates before changing how much the agent sends alone. Return to Reading Inboxes, Threads and Incremental Sync before building the event loop. Start free at molted.email (free for people, paid plans from $19 a month).


Molted Email gives an agent its own address and inbox, with inbound screening and a policy check on every send, through MCP, a CLI, or a REST API. The calls in this guide are the same ones an editor agent or a backend service uses to read a thread, preview a message, and wait until delivery is real. Visit Molted Email and open the first mailbox before the agent is allowed to write to anyone else.

The Molted team