An inbound email API accepts mail sent to an address you control and hands each message to your code as JSON. On OpenMail you create the address with one API call. Every message then arrives as a message.received event, over a signed webhook or a WebSocket, with the body, the text of any attachments and a thread ID already in it.
The mail is also stored, so you can list unread threads, search messages or download the original MIME later. Below is working code for each step, from creating the address to replying in the thread, and a comparison of nine inbound email APIs by what they hand you.
What an inbound email API does
Receiving email takes more work than sending it. Something has to answer on port 25 for your domain's MX record. It has to accept the message, check SPF, DKIM and DMARC, and filter spam.
Then it decodes the MIME tree: multipart boundaries, transfer encodings, character sets, inline images and attachments. Only after all that does your code see a sender, a subject and some text.
An inbound email API does that part and gives you the result. Products in this space fall into three groups, and the group decides how much you still build:
- Routing to your code. Mailgun, SendGrid Inbound Parse, Postmark, Amazon SES and Cloudflare Email Workers receive mail for your domain and pass it on. Storage, threads and replies are yours to build.
- Hosted inboxes. OpenMail, AgentMail, Mailtrap Inbound and Resend Inboxes create a real mailbox per address. They keep the mail, group it into threads and let you reply in place.
- Existing mailboxes. The Gmail API and similar services read mail that already lands in a person's account. That fits a tool acting for one user. It fits poorly when code needs its own address.
If you only need to catch replies to transactional mail on a domain you already send from, a routing product is fine. If an agent, a user or a workflow needs its own address with history, a hosted inbox saves you a database and a threading engine.
What to check before you pick one
These questions decide how much code you end up writing:
- What is in the push? A full body, or only IDs you have to look up with a second call?
- Attachments: inline base64, a download link, or text you can read without parsing a PDF yourself?
- Can you read the mail again tomorrow, or does it exist only in the one HTTP request you received?
- Threads: does the provider group replies, or do you match
In-Reply-ToandReferencesheaders yourself? - Reliability: how long are failed deliveries retried, can you replay one, and is there a way to receive without a public URL?
- Control: can you drop mail from unknown senders before it reaches your code, and is spam flagged?
- Addresses: can you create a new one by API in a second, on a shared domain, without touching DNS?
Step 1: create an address
One call creates a working inbox. Without a custom domain the address is on omail.sh. mailboxName sets the part before the @. Leave it out and you get a random 8-character name.
curl -X POST https://api.openmail.sh/v1/inboxes \
-H "Authorization: Bearer $OPENMAIL_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"mailboxName": "invoices",
"displayName": "Invoices",
"webhookUrl": "https://example.com/webhooks/openmail",
"forwardTo": "ops@example.com",
"forwardWhen": "needs_human"
}'{
"id": "inb_92ma4k",
"address": "invoices@omail.sh",
"displayName": "Invoices",
"webhookUrl": "https://example.com/webhooks/openmail",
"webhookSecret": "...",
"forwardTo": "ops@example.com",
"forwardWhen": "needs_human",
"forwardStatus": "pending"
}Setting webhookUrl here points this inbox's events at your URL and returns a signing secret once, in webhookSecret. Store it then, because it is never shown again.
The two forward fields are optional. forwardTo sends a copy of inbound mail to a person. forwardWhen decides which copies: always, needs_human for mail an agent shouldn't auto-handle, or webhook_failed for mail that never reached your code.
An address outside your organisation gets a confirmation link first, and nothing is forwarded until it is clicked. Spam and bulk mail are never forwarded.
To receive on your own domain, add it with POST /v1/domains, publish the MX, DKIM, MAIL FROM, SPF and DMARC records it returns, and pass domain when you create the inbox. Custom domains are on the Pro plan and above. More on creating addresses at scale is in Create an inbox per user or agent with one API call.
Step 2: receive each message as it arrives
You have two ways to get the push. They carry the same JSON, so you can switch later without touching the code that handles it.
By webhook
A per-inbox webhookUrl works for one inbox. For many inboxes, add one endpoint for the whole organisation and narrow it with inboxIds or podIds if you need to. The URL must be public HTTPS.
curl -X POST https://api.openmail.sh/v1/webhooks/endpoints \
-H "Authorization: Bearer $OPENMAIL_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/webhooks/openmail",
"events": ["message.received"],
"inboxIds": ["inb_92ma4k"]
}'Each request carries X-Timestamp, X-Signature and X-Event-Id. The signature is HMAC-SHA256 over {timestamp}.{raw body} with your secret. Here is a complete Flask handler:
import hashlib, hmac, json, os, time
from queue import Queue
from flask import Flask, request
app = Flask(__name__)
SECRET = os.environ["OPENMAIL_WEBHOOK_SECRET"]
queue = Queue() # a worker thread reads from this and runs the agent
seen = set() # use a table with a unique key on event_id in production
def valid(raw: bytes, timestamp: str, signature: str) -> bool:
signed = f"{timestamp}.{raw.decode()}".encode()
expected = hmac.new(SECRET.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature, expected)
@app.post("/webhooks/openmail")
def webhook():
raw = request.get_data() # the raw bytes: the signature covers them, not parsed JSON
timestamp = request.headers.get("X-Timestamp", "")
if not valid(raw, timestamp, request.headers.get("X-Signature", "")):
return "", 400
if abs(time.time() - int(timestamp)) > 300: # older than 5 minutes: a replay
return "", 400
event = json.loads(raw)
if event["event_id"] in seen: # at-least-once delivery: retries reuse the ID
return "", 200
seen.add(event["event_id"])
if event["event"] == "message.received":
queue.put(event) # answer inside 15 seconds; run the agent elsewhere
return "", 200Three details in that handler matter in production. Verify against the raw bytes, since a framework that parses and re-serialises the JSON changes them. Deduplicate on event_id, because delivery is at least once and the same ID comes back on every retry. Return 200 within 15 seconds and do the slow work in a queue, since a model call can take longer and a slow answer counts as a failure.
Events can also arrive out of order. If order matters, sort by occurred_at.
If the receiver is a platform that already checks Standard Webhooks signatures, paste a whsec_ secret when you create the endpoint and OpenMail signs that way instead. Paste any other value and it is sent as a bearer token, which proves the sender but not that the body is unchanged.
import base64, hashlib, hmac
def valid_standard(raw: bytes, headers, secret: str) -> bool:
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = f"{headers['webhook-id']}.{headers['webhook-timestamp']}.".encode() + raw
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
# the header can hold several space-separated signatures during a key rotation
for sig in headers.get("webhook-signature", "").split(" "):
version, _, value = sig.partition(",")
if version == "v1" and hmac.compare_digest(value, expected):
return True
return FalseWhat arrives
{
"event": "message.received",
"event_id": "3a1f9c2e-7b4d-4e8a-9c1f-2d5e6a7b8c9d",
"occurred_at": "2026-12-01T09:12:03.000Z",
"inbox_id": "inb_92ma4k",
"thread_id": "thr_xyz",
"message": {
"id": "msg_456",
"rfc_message_id": "<CAF7x2k@mail.example.com>",
"from": "billing@vendor.example",
"to": "invoices@omail.sh",
"to_recipients": ["invoices@omail.sh"],
"cc": [],
"address_names": { "billing@vendor.example": "Vendor Billing" },
"subject": "Invoice 2847",
"body_text": "Hi, the November invoice is attached.",
"attachments": [{
"id": "7891305c-988d-499f-9d59-cbc6c2c1b83d",
"filename": "invoice-2847.pdf",
"contentType": "application/pdf",
"sizeBytes": 48211,
"url": "https://api.openmail.sh/v1/attachments/msg_456/7891305c-988d-499f-9d59-cbc6c2c1b83d",
"parsedText": "Invoice #2847\nAmount due: EUR 1,250.00",
"extractionMethod": "pdf"
}],
"raw_url": "https://api.openmail.sh/v1/messages/msg_456/raw",
"received_at": "2026-12-01T09:12:02.000Z",
"category": "personal",
"auto_replyable": true,
"verdict": "clean",
"spam_score": 0.4
}
}inbox_id tells you which address the mail was for, so one handler can serve thousands of inboxes. thread_id is what you reply with. body_text is the plain-text body. The full HTML version is on the message when you fetch it later.
category sorts mail into personal, automated, marketing, bounce, spam or malicious. auto_replyable is false for automated mail, bulk mail, bounces and spam. Check it before an agent answers anything. Replying to an out-of-office notice is how two robots end up emailing each other all weekend.
Over a WebSocket, with no public URL
An agent on a laptop, in a container or behind a firewall can open a connection instead. Nothing has to be exposed, and the docs recommend this route for agents. Events stream with sub-second latency.
import asyncio, json, os
from websockets import connect
URI = "wss://api.openmail.sh/v1/ws"
HEADERS = {"Authorization": f"Bearer {os.environ['OPENMAIL_API_KEY']}"}
last_event_id = None # keep this somewhere durable in production
async def listen():
global last_event_id
async for ws in connect(URI, extra_headers=HEADERS): # reconnects on its own
try:
sub = {"type": "subscribe", "inbox_ids": ["inb_92ma4k"],
"event_types": ["message.received"]}
if last_event_id:
sub["last_event_id"] = last_event_id # replays up to 100 missed events
await ws.send(json.dumps(sub))
async for raw in ws:
event = json.loads(raw)
if event.get("event") == "message.received":
last_event_id = event["event_id"]
await handle(event)
except Exception:
continue
asyncio.run(listen())Subscribe to all inboxes or pass inbox_ids. After a disconnect, send the last event_id you handled and up to 100 missed events are replayed. A connection opened with an inbox-scoped key only ever sees that inbox's events.
The limits are 10 connections per account and 30 client messages per 10 seconds on each. The server pings every 30 seconds and drops a connection that doesn't answer within 10. If you run a webhook and a WebSocket together, you get every event twice with the same event_id.
Step 3: read mail later, without a push
Pushes are for reacting fast. Reading is for everything else: a batch job that runs hourly, a support view, an agent that starts up and needs to catch up. Every inbound message is stored, so the read API is always there.
New inbound threads start unread, sending a reply marks a thread read, and PATCH /v1/threads/{id} sets it either way. That gives you a queue with no extra infrastructure:
import os, requests
API = "https://api.openmail.sh/v1"
H = {"Authorization": f"Bearer {os.environ['OPENMAIL_API_KEY']}"}
INBOX = "inb_92ma4k"
def poll_once():
threads = requests.get(f"{API}/inboxes/{INBOX}/threads",
params={"isRead": "false", "limit": 50}, headers=H).json()
for t in threads["data"]:
thread = requests.get(f"{API}/threads/{t['id']}/messages", headers=H).json()
inbound = [m for m in thread["data"] if m["direction"] == "inbound"]
handle(thread, inbound[-1]) # newest inbound message; full history in thread["data"]
# only mark read after handling, so a crash leaves it in the queue
requests.patch(f"{API}/threads/{t['id']}", json={"isRead": True}, headers=H)GET /v1/threads/{id}/messages returns the conversation in order. Each message has direction, fromAddr, bodyText, bodyHtml and its attachments, which is the context a model needs before it answers.
Even with webhooks, run this loop now and then as a safety net. Anything your handler missed during an outage is still an unread thread.
To find one message, search. Every word must appear in the subject, body, sender or To address. Case is ignored.
# Inbound mail that mentions both words, newest first
curl "https://api.openmail.sh/v1/inboxes/inb_92ma4k/messages?direction=inbound&q=invoice%20acme&limit=20" \
-H "Authorization: Bearer $OPENMAIL_API_KEY"Agents that work from a shell can do the same through the CLI:
npm install -g @openmail/cli
openmail threads list --is-read false --json # unread threads
openmail threads get --thread-id thr_xyz --json # the whole conversation
openmail threads read --thread-id thr_xyz # mark it handled
openmail messages search --query "invoice acme" --jsonLists are paged with limit (50 by default) and offset. People can read the same inbox in Apple Mail, Outlook or Thunderbird over IMAP, with an inbox-scoped key that has mail access turned on as the password.
Step 4: attachments as text
Most inbound APIs give you the file. That is where the work starts: a PDF parser, OCR for scans, something for Word and Excel. OpenMail extracts the text when the mail arrives and puts it in parsedText on each attachment, inside the event.
Extraction covers PDFs, images and scans (by OCR), .docx, .xlsx, .pptx and .odt, CSV and TSV, and plain text formats. extractionMethod says which path ran, or why none did.
import os, requests
H = {"Authorization": f"Bearer {os.environ['OPENMAIL_API_KEY']}"}
def attachment_text(msg_id: str, att: dict) -> str:
if att.get("parsedText"): # already in the event
return att["parsedText"]
if att.get("extractionMethod") in ("unsupported", "skipped_too_large"):
return f"[{att['filename']}: no text, {att['extractionMethod']}]"
# stored before extraction existed, or you want to re-extract
r = requests.get(f"https://api.openmail.sh/v1/attachments/{msg_id}/{att['id']}/text", headers=H)
return r.json().get("text", "")
def model_input(event: dict) -> str:
m = event["message"]
parts = [f"From: {m['from']}", f"Subject: {m['subject']}", "", m["body_text"]]
for att in m["attachments"]:
parts += ["", f"--- {att['filename']} ---", attachment_text(m["id"], att)]
return "\n".join(parts) # all of this is untrusted input from a strangerThe limits: files over 10 MB aren't extracted, text stops at 50,000 characters per file, and video, audio and archives are marked unsupported. A scanned PDF can come back with little text, so check before you rely on it. The original file is at the attachment's url. It downloads with the same API key, with no signed link that expires. The full treatment, including what to do with long files and images, is in Inbound email with attachment text, ready for an LLM.
Step 5: the raw message, when you need it
Parsed JSON covers most jobs. Sometimes you need the exact bytes: to check authentication results, to archive mail for compliance, or to read a header the event doesn't carry. GET /v1/messages/{id}/raw returns the original RFC 822 message as message/rfc822, exactly as received.
import os, requests
from email import message_from_bytes, policy
H = {"Authorization": f"Bearer {os.environ['OPENMAIL_API_KEY']}"}
raw = requests.get("https://api.openmail.sh/v1/messages/msg_456/raw", headers=H).content
msg = message_from_bytes(raw, policy=policy.default) # the exact bytes that arrived
print(msg["Authentication-Results"]) # spf=pass; dkim=pass ...; dmarc=pass
print(msg["Message-ID"], msg["Date"])
for part in msg.walk():
print(part.get_content_type(), part.get_filename())The event's raw_url points to the same place. It is null when the bytes weren't kept, so check it first.
Step 6: reply in the same thread
Receiving is half the loop. Pass the threadId from the event and OpenMail sets In-Reply-To and References, so the reply lands under the original in Gmail or Outlook.
curl -X POST https://api.openmail.sh/v1/inboxes/inb_92ma4k/send \
-H "Authorization: Bearer $OPENMAIL_API_KEY" \
-H "Idempotency-Key: reply-3a1f9c2e-7b4d-4e8a-9c1f-2d5e6a7b8c9d" \
-H "Content-Type: application/json" \
-d '{
"to": "billing@vendor.example",
"threadId": "thr_xyz",
"body": "Thanks, received. Payment goes out on Friday.",
"includeQuote": false
}'Building the Idempotency-Key from the event ID means a retried webhook can't send the same reply twice. Keys are remembered for 24 hours. The step by step version, with the WebSocket loop and thread context, is in How an AI agent receives email and replies to it.
Decide who can write in
An inbound address is public. Anyone who learns it can send to it, and whatever they write ends up in your code, or in a model's context.
Sender rules filter before delivery. In allowlist mode only listed addresses or domains get through. Blocked mail is dropped before it is threaded or stored, and it fires no event.
# Only mail from vendor.example reaches this inbox. Everything else is dropped.
curl -X PUT "https://api.openmail.sh/v1/policy?inboxId=inb_92ma4k" \
-H "Authorization: Bearer $OPENMAIL_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"inbound": { "mode": "allowlist", "rules": [{ "type": "allow", "value": "vendor.example" }] }
}'Rules apply per account, per pod or per inbox, and need an account-wide key. A key scoped to one inbox gets a 403 on every policy call, so an agent can't loosen its own rules. Give each agent such a key with POST /v1/inboxes/{id}/api-keys and keep the account key on your server. More on this threat in How to keep prompt injection out of an AI agent's inbox.
When delivery fails
Every inbound pipeline eventually meets a deploy that breaks the webhook. On OpenMail, a delivery fails if your endpoint doesn't return a 2xx within 15 seconds.
Redirects count as failures too. OpenMail tries five times: at once, then after 30 seconds, 60 seconds, 2 minutes and 4 minutes. After that the delivery is marked failed.
That is a short window. Postmark retries 10 times, with gaps growing from 1 minute to 6 hours. Mailgun keeps retrying for 8 hours.
The mail itself is not lost. It is stored whether or not the webhook succeeded, so the thread stays unread until you handle it. You can replay a failed delivery from the Logs tab in the console, or with POST /v1/webhooks/deliveries/{id}/redeliver. Setting forwardWhen: "webhook_failed" sends a person a copy of exactly the mail that never reached your code.
Events that happen while an endpoint is disabled are not kept for later. Fix a broken endpoint instead of disabling it, or catch up with the unread loop afterwards.
Inbound email APIs compared
Nine services, checked against each one's own documentation on 1 December 2026.
| Provider | How mail reaches your code | Body in the push | Read it again later by API | Threads |
|---|---|---|---|---|
| OpenMail | Signed webhook or WebSocket | Yes, plus the text of each attachment (parsedText) | Yes: threads, messages, search, raw MIME | Yes |
| AgentMail | Webhook, WebSocket or polling webhook | Yes, plus extracted_text without quoted history. Left out of events for large messages | Yes | Yes |
| Mailtrap Inbound | HMAC-signed webhook or REST API | Yes, parsed JSON with attachment download URLs | Yes | Yes, per its product page |
| Resend Inboxes | inbox.email.received webhook | No. Fetch it with Retrieve Thread Email | Yes | Yes. Needs a verified domain |
| Postmark | JSON POST to your URL | Yes, attachments inline as base64, plus StrippedTextReply | Yes, inbound message search | You track them from headers |
| Mailgun | Route with forward(): form data or JSON | Yes, plus stripped-text | Only with a store() route, for up to 3 days | You track them from headers |
| SendGrid Inbound Parse | multipart/form-data POST, or the raw MIME | Yes | Not in the Inbound Parse docs | You track them from headers |
| Amazon SES | Receipt rules: S3, SNS or Lambda | Raw MIME saved to S3. The Lambda event has no body | From your own S3 bucket | You build them |
| Cloudflare Email Workers | email() handler in a Worker | Raw MIME stream. You parse it (postal-mime) | Only if your Worker stores it | You build them |
Sources: each provider's inbound docs (AgentMail, Mailtrap, Resend, Postmark, Mailgun, SendGrid, Amazon SES, Cloudflare), checked December 2026.
OpenMail
Everything above: addresses by API on a shared domain or yours, a signed webhook or a WebSocket, attachment text in the event, threads, search and the raw MIME. The weak spots are the short webhook retry window and attachment text capped at 50,000 characters per file.
AgentMail
The closest product to ours, built for agents too. It delivers by webhook, WebSocket or a polling webhook read with the Svix SDK. Its best feature is extracted_text: the new reply with quoted history, "Sent from my iPhone" lines and footers removed, in many languages.
Events for large messages leave the body out, so you call Get Message. Attachment text comes from a separate text_url, up to 250,000 characters per file, five times our cap. It covers PDFs with a text layer, Word, Excel and text files, but not images, scanned PDFs or PowerPoint.
Pick it when your agent reads long reply chains. Our OpenMail vs AgentMail page has the rest.
Mailtrap Inbound
Part of Mailtrap's sending product. You create a folder and an inbox by API, on Mailtrap's domain or yours after an MX record. Each message comes as parsed JSON with attachment download URLs, over an HMAC-signed webhook or the REST API, and its product page lists threads and replies as built in. Pick it when you already send through Mailtrap.
Resend
Resend has two inbound products. Receiving accepts mail for any address on a verified domain and fires an email.received webhook with metadata only. You fetch the body and headers from the Received emails API, and each attachment's download_url lasts one hour. To reply in thread, you set In-Reply-To yourself.
Inboxes, launched in October 2026, stores and threads mail, with folders, labels, drafts and assignment to teammates. It needs a verified domain with receiving on, or forwarding from an existing address. Its webhook also leaves out the body.
Pick it when a team and its agents share one inbox, or you already send with Resend. The side-by-side is on OpenMail vs Resend.
Postmark
Postmark posts one JSON document per message, attachments included as base64, up to 35 MB of attachments in total. StrippedTextReply holds just the new reply, for English replies that carry reply headers. MailboxHash picks up plus addressing (inbound+12345@), which is a cheap way to route mail to a record.
Failed posts are retried 10 times, from 1 minute up to 6 hours apart. Inbound message search lets you look mail up later. Pick it when you send with Postmark and want replies next to it.
Mailgun
Mailgun uses Routes: a filter such as match_recipient(".*@bar.com"), with regex captures, and actions like forward(), store() and stop(). A forward posts form data, multipart when there are attachments, or one JSON document if your URL ends in json.
stripped-text removes quoted parts and the signature block. Retries run for 8 hours. A store() route keeps a message for up to 3 days. Pick it when you need routing rules on a domain you already send from.
SendGrid Inbound Parse
SendGrid posts each message to your URL as multipart/form-data, or as the full raw MIME if you tick that option. Its docs warn that code which reads only URL-encoded fields can drop attachments in the default format. Messages should stay under 30 MB. Pick it when you're already on SendGrid and only need the push.
Amazon SES
SES receives for your domain, scans for spam and viruses, and runs receipt rules. Rules can save the raw, unmodified MIME to S3 (40 MB by default), publish to SNS, invoke Lambda or bounce. The Lambda event has no body, so the usual path is S3 plus a function that reads it.
Receiving works only in some AWS regions. Parsing, storage, threads and the API on top are yours. Pick it when you're on AWS and want to own the whole pipeline. We wrote up the trade-off in OpenMail vs Mailgun vs Amazon SES.
Cloudflare Email Workers
An email() handler in a Worker gets each message with raw, a single-use stream of the MIME, and can forward, reply or reject it. Cloudflare's docs suggest postal-mime for parsing. Storage is whatever you bind to the Worker.
Pick it when your domain is on Cloudflare and the logic fits in a function. More on OpenMail vs Cloudflare Email.
Which one to use
- You send transactional mail and only want replies on the same domain: Postmark or Mailgun inbound, next to what you already use.
- You are on AWS or Cloudflare and happy to write MIME parsing, storage and threading: SES receipt rules or Email Workers.
- A team shares an inbox with agents helping: Resend Inboxes.
- Your agent reads long reply chains and you want quote stripping done for you: AgentMail.
- You need addresses on demand by API, mail as JSON over a webhook or a WebSocket, attachment text in the event, threads and a read API, with data in the EU on every plan: OpenMail. The free plan has 3 inboxes and 3,000 emails a month.
Frequently asked questions
What is an inbound email API?
It is an API that receives email for you. Mail sent to an address you control is accepted, parsed and handed to your code as structured data, usually by webhook. Some providers also store the mail so you can list and read it later. OpenMail does both.
Can I receive email by API without running a mail server?
Yes. The provider runs the mail server. On OpenMail, one POST to /v1/inboxes creates a working address on omail.sh, and each message reaches your code as JSON over a webhook or a WebSocket. A custom domain needs the Pro plan.
Do I need a public URL to receive email?
No, not on OpenMail. Connect to wss://api.openmail.sh/v1/ws with your API key and events stream to your process. You can also poll GET /v1/inboxes/{id}/threads?isRead=false. Webhook-only providers need a public HTTPS URL.
What happens if my webhook is down when an email arrives?
OpenMail retries five times over about seven and a half minutes, then marks the delivery failed. The message is still stored, so it shows up as an unread thread. You can replay the delivery from the console or the API.
Can an inbound email API read attachments?
Yes. OpenMail extracts the text of PDFs, scans, Office files and CSVs into parsedText in the event, up to 50,000 characters per file. Files over 10 MB aren't extracted. The original file is at the attachment's url.
Is there a free inbound email API?
Yes. OpenMail's free plan has 3 inboxes, 3,000 emails a month and 3 GB of storage, with no card. Pro is €9 a month with 10 inboxes, then €1 per extra inbox.



