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/

Vercel AI SDK + Reloop: Send Email Notifications from Your AI App

Pranav Patel

Pranav Patel

Co-founderยท10 min read

Vercel AI SDK + Reloop: Send Email Notifications from Your AI App
Summary

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."
Piece
Responsibility
AI SDK
Runs the model, decides whether to call the tool, streams the reply
Your tool
Validates input, fixes the recipient, renders a safe email
Reloop
Delivers it, retries, records it in the logs, fires webhooks

1. Install

bash
npm install ai @ai-sdk/anthropic zod reloop-email

Add the keys to .env.local:

env
ANTHROPIC_API_KEY=sk-ant-...
RELOOP_API_KEY=rl_your_api_key_here

Neither key gets a NEXT_PUBLIC_ prefix. Both are used only on the server.

Create a shared Reloop client:

lib/reloop.ts
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.

lib/tools/email-user.ts
1import { tool } from "ai";
2import { z } from "zod";
3import { reloop } from "@/lib/reloop";
4
5const escapeHtml = (s: string) =>
6 s.replace(/[&<>"']/g, (c) =>
7 ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[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: z
21 .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 = body
32 .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:

Choice
Why
Recipient comes from the session, not inputSchema
A prompt injection can't redirect mail to an attacker
Fixed from address
The model can't impersonate another sender
escapeHtml on the body
Model output is untrusted; never inject it as raw HTML
Per-conversation cap
A looping model can't flood an inbox
tags with source and user_id
Every AI-triggered email is filterable in Reloop logs
Errors returned, not thrown
The model sees the failure and can tell the user

3. Wire it into a Next.js route

app/api/chat/route.ts
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:

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

jobs/export-complete.ts
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:

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

Event
Useful for
email.delivered
Confirm the notification arrived
email.bounced
Stop emailing that user; ask them to update their address
email.complained
Turn the assistant's email feature off for that user
email.opened / email.clicked
Feed engagement back into the assistant's context

Guardrail checklist

  • Recipient comes from the session or job, never from the model
  • Fixed from address on a verified domain
  • Model output HTML-escaped, or passed into a template variable
  • Per-conversation or per-user send cap
  • needsApproval for anything beyond self-notifications
  • source tag on every AI-triggered email
  • stopWhen set 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.

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