Vercel AI SDK + Reloop: Send Email Notifications from Your AI App
Pranav Patel
Co-founderยท10 min read
On this page

Give an AI SDK model a safe email tool: define it with tool() and Zod, lock the recipient on the server, send with Reloop, require approval for risky sends, and track every email the model triggers.
To let an AI SDK model send email, give it a tool whose execute function calls Reloop, and keep every risky decision on the server. The model chooses when to notify and what to say. Your code decides who receives it, which address it comes from, and how often it can fire.
This guide builds that tool with the current AI SDK (tool() with inputSchema, stopWhen), wires it into a Next.js route, and covers the guardrails that stop a confused model from emailing the wrong person.
What we're building
A chat assistant inside your app that can email the signed-in user. For example:
- "Email me a summary of this conversation."
- "Let me know when the export finishes."
- "Send me tomorrow's checklist at 9am."
1. Install
npm install ai @ai-sdk/anthropic zod reloop-emailAdd the keys to .env.local:
ANTHROPIC_API_KEY=sk-ant-...RELOOP_API_KEY=rl_your_api_key_hereNeither key gets a NEXT_PUBLIC_ prefix. Both are used only on the server.
Create a shared Reloop client:
1import { Reloop } from "reloop-email";2
3export const reloop = new Reloop({ apiKey: process.env.RELOOP_API_KEY! });2. Define the email tool
The most important design decision: the model never chooses the recipient. You create the tool per request, with the signed-in user's address baked in.
1import { tool } from "ai";2import { z } from "zod";3import { reloop } from "@/lib/reloop";4
5const escapeHtml = (s: string) =>6 s.replace(/[&<>"']/g, (c) =>7 ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!,8 );9
10export function emailUserTool(user: { id: string; email: string }) {11 let sent = 0;12
13 return tool({14 description:15 "Email the current user. Use only when they ask to be emailed or notified. " +16 "Write a short subject and a plain-language body.",17 inputSchema: z.object({18 subject: z.string().min(3).max(120),19 body: z.string().min(10).max(4000),20 sendAt: z21 .string()22 .datetime()23 .optional()24 .describe("ISO 8601 time to send later, e.g. a reminder"),25 }),26 execute: async ({ subject, body, sendAt }) => {27 if (sent >= 2) {28 return { ok: false, reason: "Email limit for this conversation reached." };29 }30
31 const paragraphs = body32 .split(/\n{2,}/)33 .map((p) => `<p>${escapeHtml(p)}</p>`)34 .join("");35
36 const { response, emailError } = await reloop.mail.send({37 from: "Acme Assistant <assistant@mail.acme.com>",38 to: user.email,39 subject,40 html: paragraphs,41 text: body,42 scheduled_at: sendAt,43 tags: [44 { name: "source", value: "ai_assistant" },45 { name: "user_id", value: user.id },46 ],47 });48
49 if (emailError) {50 console.error("Reloop send failed", emailError.status, emailError.body);51 return { ok: false, reason: "The email could not be sent." };52 }53
54 sent++;55 return { ok: true, messageId: response.messageId, scheduled: Boolean(sendAt) };56 },57 });58}Why it's built this way:
inputSchemafrom addressescapeHtml on the bodytags with source and user_id3. Wire it into a Next.js route
1import { anthropic } from "@ai-sdk/anthropic";2import { convertToModelMessages, stepCountIs, streamText, type UIMessage } from "ai";3import { getSession } from "@/lib/auth";4import { emailUserTool } from "@/lib/tools/email-user";5
6export async function POST(req: Request) {7 const session = await getSession(req);8 if (!session) return new Response("Unauthorized", { status: 401 });9
10 const { messages }: { messages: UIMessage[] } = await req.json();11
12 const result = streamText({13 model: anthropic("claude-sonnet-5-5"),14 system:15 "You are Acme's in-app assistant. Only send email when the user asks " +16 "for it. Confirm what you sent in one sentence.",17 messages: await convertToModelMessages(messages),18 tools: { emailUser: emailUserTool(session.user) },19 stopWhen: stepCountIs(5),20 });21
22 return result.toUIMessageStreamResponse();23}stopWhen: stepCountIs(5) lets the model call the tool, read the result, and write a final reply, while capping how many round trips one request can take.
On the client, use useChat from @ai-sdk/react as usual. Nothing about email leaks into the browser: it only sees the assistant's text and the tool result.
4. Require approval for sends
For a "remind me tomorrow" feature, auto-sending is fine. For anything that goes to someone other than the current user, or anything irreversible, make a human approve it first.
The AI SDK supports this on the tool itself:
1return tool({2 description: "Email the current user.",3 inputSchema: z.object({ subject: z.string(), body: z.string() }),4 needsApproval: true,5 execute: async ({ subject, body }) => {6 /* same as above */7 },8});With needsApproval, the SDK pauses before execute and surfaces an approval request in the chat UI. The email is sent only after the user approves it. You can also pass a function to needsApproval to require approval conditionally, for example only when sendAt is set.
5. Background jobs: notify when work finishes
Chat is one trigger. The more useful one is often a background job: an export, a report, a long-running agent task. Run the model when the job completes and let it write the notification.
1import { anthropic } from "@ai-sdk/anthropic";2import { generateText, stepCountIs } from "ai";3import { emailUserTool } from "@/lib/tools/email-user";4
5export async function onExportComplete(job: ExportJob) {6 await generateText({7 model: anthropic("claude-sonnet-5-5"),8 system: "Write a short, specific notification. No marketing language.",9 prompt:10 `The user's export "${job.name}" finished with ${job.rows} rows ` +11 `and ${job.warnings.length} warnings: ${job.warnings.join("; ")}. ` +12 `Download link: ${job.url}. Email them about it.`,13 tools: { emailUser: emailUserTool(job.user) },14 stopWhen: stepCountIs(3),15 });16}The model turns raw job data into a useful message: it mentions the warnings that matter and skips the ones that don't. Reloop handles the delivery.
6. Templates for consistent design
Letting the model write the words doesn't mean letting it write the layout. Keep your brand, header and footer in a Reloop template, and pass the model's text in as a variable:
1const { response, emailError } = await reloop.mail.send({2 from: "Acme Assistant <assistant@mail.acme.com>",3 to: user.email,4 subject,5 template: {6 id: "tmpl_assistant_message",7 variables: { name: user.name, summary: body },8 },9 tags: [{ name: "source", value: "ai_assistant" }],10});Your design team owns the template (or drafts it with AI). The model only fills in summary.
7. Observability
Every send the model triggers shows up in Reloop like any other email: recipient, subject, status and delivery events. Because of the tags, you can answer questions like "how many emails did the assistant send yesterday?" by filtering on source = ai_assistant.
To react to what happens next, subscribe a webhook to the email events you care about:
email.deliveredemail.bouncedemail.complainedemail.opened / email.clickedGuardrail checklist
- Recipient comes from the session or job, never from the model
- Fixed
fromaddress on a verified domain - Model output HTML-escaped, or passed into a template variable
- Per-conversation or per-user send cap
-
needsApprovalfor anything beyond self-notifications -
sourcetag on every AI-triggered email -
stopWhenset so a request can't loop forever
FAQ
Yes. The tool is plain AI SDK, so swap anthropic(...) for any provider
the AI SDK supports. Nothing in the Reloop code changes.
It can if you build that tool, but don't make it the default. Use an
allowlist (for example, the user's teammates), require approval with
needsApproval, and log who approved each send. If the agent needs its
own address and has to read replies too, see
how to give an AI agent its own email address.
MCP is great for assistants like Claude, Cursor or Claude Code acting on your own Reloop account. Inside your product, a narrow tool like the one above is safer, because you control exactly what the model can do. See the MCP server docs.
Send through the REST API with an Idempotency-Key header derived from
the job or message ID. Retries with the same key won't send twice. See
idempotency.
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.


