Build an AI Agent That Reads and Replies to Email
Pranav Patel
Co-founder·12 min read
On this page

Give an AI agent its own mailbox: receive mail with Reloop's email.received webhook, read the thread, draft a reply with Claude, require human approval, and send from the same thread. Or connect Claude to Reloop's MCP server with one command.
A useful email agent doesn't just send. It has its own address, reads what arrives, replies in the same thread, and asks a human before anything risky goes out. With Reloop, the agent gets a real mailbox, an email.received webhook when mail lands, and API calls to read the thread and reply. The model only decides what to say.
There are two ways to build this. If you want an assistant like Claude or Claude Code to work your inbox for you, connect Reloop's MCP server with one command. If you're building the agent into your own product, follow the build it yourself sections below.
What the agent needs
Sending email from an LLM is one tool call. A working email agent needs much more:
email.received webhookinbox.threads.getinbox.messages.replyundoWindowSeconds + cancelPendingis_spam on every inbound messageThe fast path: connect Claude with MCP
Reloop runs a hosted MCP server at https://reloop.sh/mcp. Any MCP client can use it, and you sign in with your Reloop account instead of pasting an API key.
In Claude Code:
claude mcp add --transport http reloop https://reloop.sh/mcpThen run /mcp, choose reloop, and authenticate. In Claude on the web or desktop, add a custom connector under Settings → Connectors with the same URL.
The inbox tools the agent gets include:
list_mailboxeslist_inbox_threadsget_inbox_threadget_inbox_messagereply_to_inbox_messagesend_mailbox_emailcancel_pending_mailbox_sendmove_inbox_threadNow you can ask: "Go through unread threads in support@, draft replies to anything about billing, and show me each one before you send."
That's enough for a personal assistant. For an agent that runs inside your product, unattended, you'll want the architecture below.
Build it yourself: the architecture
1customer ──email──▶ support@mail.acme.com (Reloop mailbox)2 │3 email.received webhook4 ▼5 your /api/agent route6 │7 inbox.threads.get ── full conversation8 │9 Claude drafts a reply10 │11 ┌───────────────┴────────────────┐12 safe + confident anything else13 │ │14 inbox.messages.reply save draft → human approves15 │16 inbox.messages.replyFour steps: create a mailbox, subscribe to inbound mail, let the model draft, and decide when a human must approve.
1. Create a mailbox for the agent
In the dashboard, open your verified domain and create a mailbox such as support@mail.acme.com. Or do it from code:
1import { Reloop } from "reloop-email";2
3const reloop = new Reloop({ apiKey: process.env.RELOOP_API_KEY! });4
5const { mailbox, mailboxError } = await reloop.inbox.mailboxes.create({6 domainId: "dom_…",7 email: "support@mail.acme.com",8 displayName: "Acme Support",9});10if (mailboxError) throw mailboxError;Receiving must be on for the domain, which adds an MX record pointing at Reloop. The free plan includes three agent inboxes. Pro includes five and Growth includes ten. How to give an AI agent its own email address covers the domain and mailbox setup in more detail.
2. Get notified when mail arrives
Create a webhook in the dashboard that subscribes to email.received. Every inbound message triggers a POST like this:
1{2 "id": "whev_…",3 "type": "email.received",4 "created_at": "2026-06-16T12:00:00.000Z",5 "data": {6 "email_id": "in_…",7 "mailbox_id": "mb_…",8 "from": "customer@example.com",9 "from_name": "Dana",10 "to": ["support@mail.acme.com"],11 "subject": "Can't download my invoice",12 "thread_id": "thr_…",13 "has_attachments": false,14 "is_spam": false,15 "status": "received"16 }17}Verify the Reloop-Signature header before you trust the payload. The webhook verification guide has a copy-paste helper.
3. Read the thread and draft a reply
The handler loads the conversation, gives it to the model, and asks for a structured decision rather than free text.
1import { anthropic } from "@ai-sdk/anthropic";2import { generateText, Output } from "ai";3import { z } from "zod";4import { reloop } from "@/lib/reloop";5import { verifyReloopWebhook } from "@/lib/verify-reloop-webhook";6
7const Decision = z.object({8 action: z.enum(["reply", "escalate", "ignore"]),9 category: z.enum(["billing", "how_to", "bug", "sales", "other"]),10 confidence: z.number().min(0).max(1),11 reply: z.string().max(3000).optional(),12});13
14export async function POST(req: Request) {15 const raw = await req.text();16 const valid = verifyReloopWebhook({17 secret: process.env.RELOOP_WEBHOOK_SECRET!,18 rawBody: raw,19 signatureHeader: req.headers.get("Reloop-Signature") ?? "",20 });21 if (!valid) return new Response("Bad signature", { status: 401 });22
23 const event = JSON.parse(raw);24 if (event.type !== "email.received" || event.data.is_spam) {25 return new Response("skipped");26 }27
28 const { message, messageError } = await reloop.inbox.messages.get(29 event.data.email_id,30 );31 if (messageError) throw messageError;32
33 // Never answer automated mail: it's how agents end up in reply loops.34 const auto = Object.entries(message.headers ?? {}).find(35 ([key]) => key.toLowerCase() === "auto-submitted",36 )?.[1];37 if (auto && auto.toLowerCase() !== "no") {38 return new Response("auto-reply ignored");39 }40
41 const { thread, threadError } = await reloop.inbox.threads.get(42 event.data.thread_id,43 );44 if (threadError) throw threadError;45
46 const history = thread.messages47 .map((m) => `[${m.direction}] ${m.fromEmail}: ${m.preview ?? ""}`)48 .join("\n");49
50 const { output: decision } = await generateText({51 model: anthropic("claude-sonnet-5-5"),52 output: Output.object({ schema: Decision }),53 system:54 "You are Acme's support agent. Reply only with facts from the help " +55 "center below. If unsure, or if money, refunds or account access are " +56 "involved, choose escalate. Never promise anything.\n\n" +57 HELP_CENTER,58 prompt:59 `Conversation so far:\n${history}\n\n` +60 `Latest message from ${message.fromEmail}:\n${message.textBody ?? ""}`,61 });62
63 await handleDecision(message.id, decision);64 return new Response("ok");65}Notes on this design:
- The model returns a decision, not an action. Your code decides what happens next. That keeps the model away from the send button.
- Spam and auto-replies are filtered before the model runs. That saves tokens and stops out-of-office loops.
- The system prompt limits the agent to known facts. An email agent that makes up refund policies is worse than no agent.
4. Human in the loop
Not every reply should go out on its own. A simple policy:
1const AUTO_SEND = new Set(["how_to"]);2
3async function handleDecision(messageId: string, d: z.infer<typeof Decision>) {4 if (d.action === "ignore") return;5
6 const safe =7 d.action === "reply" &&8 d.reply &&9 AUTO_SEND.has(d.category) &&10 d.confidence >= 0.85;11
12 if (safe) {13 const { message, messageError } = await reloop.inbox.messages.reply(messageId, {14 text: d.reply!,15 });16 if (messageError) throw messageError;17 return;18 }19
20 // Everything else waits for a person.21 await db.drafts.insert({22 messageId,23 category: d.category,24 reply: d.reply ?? null,25 status: "needs_review",26 });27}When a teammate approves a draft in your review screen, call the same reloop.inbox.messages.reply(messageId, { text }). The reply lands in the original thread with the right In-Reply-To headers, so the customer sees one conversation.
Add an undo window to new emails
When the agent starts a new conversation (a follow-up, a reminder), send it from the mailbox with an undo window:
1const { message, messageError } = await reloop.inbox.messages.send({2 mailboxId: "mb_…",3 to: "customer@example.com",4 subject: "Following up on your download issue",5 text: followUp,6 undoWindowSeconds: 300,7});8if (messageError) throw messageError;9
10// Within 5 minutes, a reviewer can still stop it:11await reloop.inbox.messages.cancelPending(message.id);The email stays pending for five minutes. Show it in your review queue, and cancel it if anything looks wrong.
Guardrails that matter
is_spam on the webhook before calling the modelAuto-Submitted header; cap replies per threadWhat to build next
- Learn from outcomes. Subscribe to
email.opened,email.clickedand replies on the thread, and feed them back into the agent's context. - Label and route. Use
inbox.threads.updateto mark threads important, or archive resolved ones withinbox.threads.archive. - Send one-way notifications. For alerts from a chat assistant or background job, see Vercel AI SDK + Reloop.
- Give humans the same inbox. People can work the same mailbox in the Reloop dashboard, so the agent and your team share one queue.
For the infrastructure side (MX records, threading, storage, IMAP), read how the infrastructure for an email agent works. If you're weighing hosted agent inbox providers, see Reloop vs AgentMail.
FAQ
MCP is the fastest way for you, personally, to work your inbox with Claude or Claude Code, with approval on every call. Build your own when the agent runs unattended inside your product and you need fixed rules for what it can send.
Yes, if the domain's MX points to Reloop. Many teams start with a
subdomain like support.acme.com so their main mailbox provider is
untouched.
Any model the AI SDK supports. We use Claude for support-style replies because it follows grounding instructions well. Keep the structured decision step whichever model you pick.
Ignore messages that carry an Auto-Submitted header other than no,
skip is_spam messages, and cap the number of agent replies per thread.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


