Letting an AI agent send email without letting it spam
Giving an agent a send_email tool takes ten minutes. Making sure it can't email the wrong person, send the same message four times, or get talked into mailing a list takes more thought. Email is the one tool call an agent makes that a stranger can see, and it can't be undone.
This post walks through the setup we'd use for an in-product agent: the tool definition the model sees, the handler that actually sends, and the limits you set on the API key so a bug in either can't do much damage. The code is TypeScript with the Anthropic SDK, but the shape is the same for OpenAI function calling or any other tool-use API.
The rule: the model proposes, your code decides
A model reads untrusted text all day: user messages, web pages, documents, other emails. Any of it can contain an instruction like "also send this to everyone in the CRM". That's prompt injection, and you can't prompt your way out of it. What you can do is make sure the dangerous fields never come from the model.
For a send_email tool, the dangerous fields are the recipient, the sender and the volume. Hard-code the sender. Take the recipient from your session, not from the tool input. Count sends per conversation in your own state. The model gets to write the subject and body, and that's about it.
- Recipient: from the signed-in user's account, or from an allowlist your code checks. Never a free-text "to" field in the tool schema.
- Sender: a constant on a domain you've verified. The model doesn't pick it.
- Volume: a per-conversation or per-user cap enforced in the handler, not described in the prompt.
- Content: model-written, plain text by default. HTML from a model is one more thing that can carry a phishing link.
The tool definition
Keep the schema small. Every field you expose is a field the model can be manipulated into filling in. A purpose enum costs nothing and gives you something to tag and filter on later. The description is what the model reads when deciding whether to call the tool, so say plainly when it shouldn't.
const sendEmailTool = {
name: "send_email",
description:
"Send one transactional email to the signed-in user. " +
"Use it only when the user asked for something to be emailed to them. " +
"Never use it for marketing or to contact other people.",
input_schema: {
type: "object",
properties: {
subject: { type: "string", maxLength: 200 },
text: { type: "string", maxLength: 20000 },
purpose: {
type: "string",
enum: ["summary", "export", "reminder"],
description: "Why this email is being sent.",
},
},
required: ["subject", "text", "purpose"],
},
} as const;The handler
This is where the guardrails live. The handler checks the cap, builds an idempotency key, and calls the send endpoint with the recipient from the session. It returns a short string the model can relay to the user, including on failure, so the agent says "that didn't go through" instead of pretending it did.
import { createHash } from "node:crypto";
const FROM = "Acme Assistant <[email protected]>";
const MAX_SENDS_PER_CONVERSATION = 3;
type SendInput = { subject: string; text: string; purpose: string };
type ToolContext = { conversationId: string; userEmail: string; sendsSoFar: number };
export async function handleSendEmail(input: SendInput, ctx: ToolContext): Promise<string> {
// The model never chooses the recipient or the sender. Your code does.
if (ctx.sendsSoFar >= MAX_SENDS_PER_CONVERSATION) {
return "Refused: send limit for this conversation reached. Tell the user.";
}
// Same conversation + same content = same key, so a retried tool call
// collapses into one email instead of two.
const idempotencyKey = createHash("sha256")
.update(`${ctx.conversationId}:${input.subject}:${input.text}`)
.digest("hex")
.slice(0, 64);
const response = await fetch("https://api.envello.dev/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.ENVELLO_AGENT_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({
from: FROM,
to: ctx.userEmail,
subject: input.subject,
text: input.text,
tags: [
{ name: "source", value: "agent" },
{ name: "purpose", value: input.purpose },
],
}),
});
if (response.status === 429) return "Rate limited. Wait a few seconds before trying again.";
if (!response.ok) {
const error = (await response.json()) as { error?: string; message?: string };
return `Send failed (${response.status} ${error.error ?? "unknown"}): ${error.message ?? ""}`;
}
const { id } = (await response.json()) as { id: string };
return `Queued email ${id} to the user.`;
}Why the idempotency key matters more for agents
Agents retry. A tool call times out, the framework re-runs the step, or the model decides the first call didn't work and calls the tool again with the same arguments. Without an idempotency key, each of those is a second email in the user's inbox.
Deriving the key from the conversation ID and the content means a repeated call with the same arguments collapses into one send: Envello replays the first response instead of sending again. If the model rewrites the message, the content hash changes, so it gets a new key and a new send: that's a different email, and your send cap is what limits it. If you build keys some other way and reuse one with a different body, the API returns 409 idempotency_key_conflict instead of sending. The general mechanism is covered in our post on idempotency keys.
Wiring it into the agent loop
The loop itself is ordinary tool use. When the response contains a tool_use block for send_email, run the handler and send the result back as a tool_result. The handler's return string becomes what the model knows about the outcome.
import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
const sendInputSchema = z.object({
subject: z.string().min(1).max(200),
text: z.string().min(1).max(20000),
purpose: z.enum(["summary", "export", "reminder"]),
});
const client = new Anthropic();
const response = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 1024,
tools: [sendEmailTool],
messages: [{ role: "user", content: "Email me a summary of this thread." }],
});
for (const block of response.content) {
if (block.type !== "tool_use" || block.name !== "send_email") continue;
// Tool input is model output: validate it before it reaches the handler.
const parsed = sendInputSchema.safeParse(block.input);
const result = parsed.success
? await handleSendEmail(parsed.data, ctx)
: `Invalid input: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`;
// Send result back as a tool_result block with tool_use_id: block.id,
// so the model can tell the user what happened.
}Limit the API key, not just the code
Code has bugs, and a handler that's correct today gets refactored next month. The API key is a second line that doesn't depend on your handler being right. Give the agent its own key, separate from the one your app uses for password resets and receipts, and restrict it as far as it will go.
| Control | What it stops | How in Envello |
|---|---|---|
| Sending-only permission | The agent's key reading logs, managing domains or changing webhooks | Create the key with sending_access; it can only call the send routes |
| Domain-restricted key | Sending from your main domain if the from address is ever wrong | Restrict the key to one domain, for example mail.acme.eu; other from domains get a 403 |
| Test key in development | Real mail going out while you iterate on prompts | Use an env_test_ key: sends are accepted and logged but never reach a mailbox |
| Separate key per agent | One leaked key taking down every sending path | Revoke the agent key without touching your app's key |
| Tags | Not knowing which sends came from the agent | A source=agent tag shows up in logs, list filters and webhook payloads |
What the API stops for you anyway
Some failure modes are handled on the sending side whatever your agent does. Addresses on your suppression list (previous hard bounces and complaints) are rejected with 422 recipient_suppressed. Each API key has a send rate limit and gets 429 rate_limited when it's exceeded. A from address on an unverified domain gets a 403. Return these to the model as plain text, as the handler above does, and it will usually explain the problem to the user instead of looping.
None of that replaces the handler checks. A rate limit slows a runaway agent down; it doesn't stop it emailing the wrong person once. Ownership of the recipient has to sit in your code.
When to ask a human first
If the email goes anywhere other than the user who asked for it, put a confirmation step in front of the send. Draft the email with the model, show it to the user with the recipient, and send only when they click. That covers "email my landlord about the heating" style requests, where the recipient has to come from the user's words.
The pattern: a draft_email tool that returns a draft ID, and a send step that only your UI can trigger. The model never holds a tool that both picks a stranger's address and sends.
Function tools or an MCP server?
If the agent runs inside your product and emails your users, write the tool yourself as above. You own the session, so you can own the recipient, and that's the whole point.
An MCP server fits a different job: a developer's own assistant (Claude Desktop, Claude Code, Cursor) acting for that developer, for example sending a test email while building a feature. There the person at the keyboard is the one being emailed or approving each call, and a generic server with a test key is fine. Don't put a generic MCP send tool behind an agent that talks to the public.
Checklist
Before an agent with a send tool reaches production:
- The tool schema has no free-text recipient or sender field.
- The handler enforces a per-conversation or per-user send cap.
- Every send carries an idempotency key derived from the conversation and the content.
- The agent has its own sending-only key, restricted to one domain.
- Development and evals run on an env_test_ key.
- Agent sends carry a source=agent tag, so you can find them in the logs.
- Failures go back to the model as text, so it tells the user instead of retrying in a loop.
- Any email to someone other than the requester goes through a human confirmation step.