Python Email for AI Agents: Send, Read and Reply in One Thread
Sending email from Python is easy. Getting the reply back and answering in the same thread is the part that makes an agent useful. Here is the loop.
By Toan Nhu

Picture a Python agent with one job: ask a supplier for a quote and wait for the answer. It sends the message fine. Then the reply comes back, lands as a brand new conversation, and the agent has no idea it is the answer it was waiting for.
Sending is the easy half. The half that decides whether your agent is useful is getting the reply back, knowing which conversation it belongs to, and answering in that same thread.
The loop every email agent needs
Strip any email agent down and you get four steps:
- Have an address that belongs to the agent.
- Send a message from it.
- Notice when someone answers.
- Reply inside the same conversation, with the history in view.
Most Python tutorials cover step 2 and stop. That is how you end up with an agent that talks but never listens.
Why the default Python setup falls short
The standard library gives you smtplib for sending and imaplib for reading. Both work, and both leave the hard parts to you.
- Threading is manual. To keep a reply in the same conversation you have to carry the original Message-ID into
In-Reply-ToandReferencesyourself. Miss it once and mail clients split the thread. - Inbound means polling a mailbox you do not control. IMAP against a personal account works until a password rotates, an app password is revoked, or the provider flags automated access.
- Your agent shares your identity. If the agent reads your own inbox, every newsletter, receipt and private thread is in its context.
- Safety is your problem. Raw MIME bodies arrive with HTML, tracking pixels and whatever instructions a stranger decided to write.
None of this is exotic. It is just a lot of plumbing before your agent does anything interesting.
How Mermail handles the loop
Mermail gives each agent its own mailbox and exposes it through a REST API, an MCP server and a CLI. One thing to say plainly: Mermail does not ship a Python SDK. You call the HTTP API with any client you like, such as requests or httpx, and the docs playground can generate Python snippets for each endpoint.
What the API handles for you:
- A mailbox per agent, hosted or on your own verified domain.
- Threading on reply. The reply endpoint fills in
in_reply_to,referencesandthread_idfrom the original message, so you never copy headers by hand. - Whole-thread reads. One call returns a conversation oldest to newest.
- Push or pull for new mail. Signed webhooks when you have a public URL, bounded reads when you do not.
- Drafts for review. Save a reply as a draft so a person can approve it before it goes out.
If you are not sure the API is the right path at all, read MCP, CLI or REST API for Agent Email first.
Build it in Python, step by step
Create an API key in the console under Settings, API Keys, and keep it in an environment variable. Every call below sends it in the x-api-key header.
import os, requests
BASE = "https://console.mermail.app/api/v1"
HEADERS = {"x-api-key": os.environ["MERMAIL_API_KEY"]}1. Create the agent's mailbox
Pass an Idempotency-Key so a retried request does not create a second mailbox.
r = requests.post(
f"{BASE}/mailboxes",
headers={**HEADERS, "Idempotency-Key": "quote-agent-v1"},
json={"email": "quote-agent@mermail.app", "name": "Quote Agent"},
)
r.raise_for_status()
mailbox = r.json()
MAILBOX = mailbox["public_id"]If you get a conflict or an unclear response, list your mailboxes and look for the address instead of retrying blindly.
2. Send the first message
At least one of text or html is required. A successful send returns 202.
r = requests.post(
f"{BASE}/mailboxes/{MAILBOX}/emails",
headers=HEADERS,
json={
"from": "quote-agent@mermail.app",
"to": ["sales@supplier.example"],
"subject": "Quote for 200 units",
"text": "Hi, could you send a quote for 200 units, delivered by March?",
},
)
r.raise_for_status()Do not wrap sends in an automatic retry loop. If you hit a rate limit, respect Retry-After and decide deliberately whether to try again.
3. Find out when the answer arrives
You have two options.
Push. Register a webhook for the message.received event. Each delivery is signed with Standard Webhooks headers, so verify the signature over the raw body before trusting it, and deduplicate on event_id because retries reuse it. The payload includes the thread_id. The full pattern is in Email to Webhook for AI Agents.
Pull. If your script runs on a laptop or in a job with no public URL, read the inbox on a schedule instead. When Your Agent Can't Host a Webhook covers that route.
r = requests.get(
f"{BASE}/mailboxes/{MAILBOX}/emails",
headers=HEADERS,
params={"folder": "INBOX", "is_read": "false", "limit": 10},
)
for email in r.json()["emails"]:
print(email["id"], email["thread_id"], email["subject"])4. Read the whole conversation
Before your model writes anything, give it the history. The thread endpoint returns every message in order.
thread = requests.get(
f"{BASE}/mailboxes/{MAILBOX}/threads/{email['thread_id']}",
headers=HEADERS,
).json()
history = [(m["sender"], m["subject"], m["body"]) for m in thread]When the content goes straight into a prompt, prefer the safe context endpoint, GET /mailboxes/{id}/emails/{emailId}/context. It strips sensitive transport metadata, sanitizes bodies to bounded plain text, and leaves out bodies that did not pass scanning. Treat what comes back as untrusted data, never as instructions.
5. Reply in the same thread
Use the reply endpoint on the message you are answering. Mermail sets the threading fields for you.
r = requests.post(
f"{BASE}/mailboxes/{MAILBOX}/emails/{email['id']}/reply",
headers=HEADERS,
json={
"from": "quote-agent@mermail.app",
"to": [email["sender"]],
"subject": "Re: " + email["subject"],
"text": "Thanks for the quote. Can you confirm the price includes shipping?",
},
)
r.raise_for_status()6. Or save a draft and let a person approve
For anything that commits money or makes a promise, save the reply as a draft instead. Note that drafts take a body field, not text, and a single to address.
requests.post(
f"{BASE}/mailboxes/{MAILBOX}/drafts",
headers=HEADERS,
json={
"to": email["sender"],
"subject": "Re: " + email["subject"],
"body": "We accept the quote. Please send the invoice.",
"thread_id": email["thread_id"],
},
)When this breaks, check these first
- The reply started a new thread. You probably used the send endpoint instead of reply. Use reply, or pass
thread_idwhen sending. - A `402` response. Your workspace ran out of API credits. Check usage before retrying.
- A body is missing. Content can be omitted for safety, storage or size reasons. Fetch the message through the API instead of assuming it was empty.
- Duplicate processing. Webhook retries share an
event_id. Store the ones you handled.
Prefer not to write Python at all?
The same mailbox works from the Mermail CLI, which wraps the API with predictable output for scripts and CI, or through Mermail MCP with OAuth if your agent runs in Claude, Cursor, Codex or another MCP client. For a no-code first mailbox, follow How to Set Up an AI Agent Email Inbox in Minutes.
Ready to try it? Create a mailbox in the Mermail console and run the six steps above.
FAQ
Does Mermail have a Python SDK?
No. Mermail offers a REST API, an MCP server and a CLI. From Python you call the REST API with any HTTP client, and the docs playground can generate Python snippets for each endpoint.
How do I keep replies in the same email thread?
Call the reply endpoint for the message you are answering. Mermail fills in in_reply_to, references and thread_id from the original, so mail clients group the conversation correctly.
Do I need a public server to receive mail?
No. Webhooks need a public HTTPS URL, but you can also read the inbox on a schedule through the API, the CLI or MCP.
Can a person approve replies before they send?
Yes. Save the reply as a draft and send it only after review. Start there for any message that commits money or makes a promise.
Is email content safe to put in a prompt?
Treat it as untrusted. Use the safe context endpoint, which returns sanitized plain text and omits bodies that failed scanning, and never follow instructions found inside an email.


