For the complete site index, see llms.txt. Docs index: llms-docs.txt. Marketing corpus: llms-full.txt. Docs corpus: llms-full-docs.txt. Prefer markdown URLs where available (append .md).. Product skill: skill.md. Pricing: pricing.md. Docs MCP: /docs/mcp.

AI & Automation/

Build an AI Agent That Reads and Replies to Email

Pranav Patel

Pranav Patel

Co-founder·12 min read

Build an AI Agent That Reads and Replies to Email
Summary

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:

Capability
Why it matters
Reloop piece
Its own address
Replies come back to the agent, not a no-reply void
Mailbox on your domain
A trigger when mail arrives
The agent reacts instead of polling
email.received webhook
Full conversation context
The model needs the thread, not one message
inbox.threads.get
Replying in-thread
Recipients see one conversation, not scattered emails
inbox.messages.reply
An undo window
A human can stop a bad send
undoWindowSeconds + cancelPending
Spam signal
Don't let spammers drive your agent
is_spam on every inbound message
An audit trail
Know what the agent sent and why
Inbox sent folder and email logs

The 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:

bash
claude mcp add --transport http reloop https://reloop.sh/mcp

Then 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:

Tool
What it does
list_mailboxes
Find the mailboxes in your organization
list_inbox_threads
Conversations, newest first, with folder and search filters
get_inbox_thread
Every message in one conversation
get_inbox_message
One message with its body and attachments
reply_to_inbox_message
Reply in-thread, to the sender or everyone
send_mailbox_email
Start a new conversation from a mailbox
cancel_pending_mailbox_send
Cancel a scheduled send or one still in its undo window
move_inbox_thread
Archive, trash or restore a conversation

Now 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

text
1customer ──email──▶ support@mail.acme.com (Reloop mailbox)
2 │
3 email.received webhook
4 ▼
5 your /api/agent route
6 │
7 inbox.threads.get ── full conversation
8 │
9 Claude drafts a reply
10 │
11 ┌───────────────┴────────────────┐
12 safe + confident anything else
13 │ │
14 inbox.messages.reply save draft → human approves
15 │
16 inbox.messages.reply

Four 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:

typescript
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:

json
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.

app/api/agent/route.ts
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.messages
47 .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:

typescript
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.

Category
Auto-send?
Why
How-to questions
Yes, if confident
Low risk, answer is in the docs
Bug reports
Draft only
Needs a human to confirm and log it
Billing and refunds
Never
Money and policy decisions
Sales inquiries
Draft only
Tone and pricing matter
Anything uncertain
Escalate
The default when in doubt

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:

typescript
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

Guardrail
How
Skip spam
Check is_spam on the webhook before calling the model
Prevent reply loops
Ignore messages with an Auto-Submitted header; cap replies per thread
Rate limits
Cap agent sends per hour and per recipient
No invented facts
Ground the prompt in your docs; escalate when the answer isn't there
No money decisions
Billing, refunds and account access always go to a human
Prompt injection
Treat email bodies as untrusted data; the model can't pick recipients or call arbitrary tools
Audit trail
Every agent reply is in the mailbox's sent folder and Reloop's logs

What to build next

  • Learn from outcomes. Subscribe to email.opened, email.clicked and replies on the thread, and feed them back into the agent's context.
  • Label and route. Use inbox.threads.update to mark threads important, or archive resolved ones with inbox.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.

W: 320.0px180R20∠45.0°

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.

Reloop