8 rules I give AI coding agents before they write email code
Ask a coding agent to "add email to my app" and it has to guess three things: where the send call runs, what happens when a request fails, and where the API key lives. When it guesses wrong, you don't find out in the di
Ask a coding agent to "add email to my app" and it has to guess three things: where the send call runs, what happens when a request fails, and where the API key lives.
When it guesses wrong, you don't find out in the diff. You find out later, when a password reset arrives twice, a receipt never arrives, or the key turns up in a client bundle.
So I stopped saying "add email" and started giving agents a short list of rules first. These are the eight I use, with the code they produce.
1. List the emails before writing any code
The first instruction isn't about code at all:
Read the project first. Then reply before writing code: list every email the app needs, say where each one is triggered, and ask me for anything missing.
This one rule fixes more than the other seven. The agent finds the sign-up flow, the password reset and the receipt hook, and you catch the one it missed (usually the "your plan is ending" email) before there's a pull request to untangle.
2. Send from the server only, and keep the key out of the chat
Call the email API only from server code: API routes, server actions, background jobs. Never from browser or mobile code. Never hard-code, log or commit the key.
Agents follow the shortest path. If the button that triggers the email is in a React component, the shortest path is a fetch right there in the component, with the key in a NEXT_PUBLIC_ variable.
I also add one line that has nothing to do with code:
Never ask me to paste the key into this chat. If I paste one, don't use it. Tell me to revoke it and create a new one.
A key pasted into a chat lives in a transcript you don't control. The agent only needs the name of the environment variable, never the value.
3. Give every send an idempotency key built from the event
Send an Idempotency-Key header built from the event, for example
password-reset/<userId>/<tokenId>, so a retry never sends the email twice.
Without this, rule 4 is dangerous. A request times out, your code retries, and the first request had actually gone through: the user gets two identical emails.
The key has to come from the event, not from a random UUID generated per attempt. A random key is different on every retry, so it protects against nothing.
4. Retry only what's worth retrying
Retry only network errors, timeouts, 429 and 5xx responses, with backoff (1s, 2s, 4s) or the retry-after header. Never retry other 4xx errors.
Agents tend to write one of two things: no retries at all, or a loop that retries everything. Retrying a 400 invalid_from_address three times won't fix it, and it hides the real error behind three log lines.
5. Set a timeout
Use the platform's fetch or HTTP client with a 10-second timeout.
fetch has no timeout by default. A slow email API then becomes a slow sign-up endpoint, and the user stares at a spinner while your server waits for a receipt to send.
6. Put it in one small module
Put the client in one module, for example
lib/email, that exportssendEmail(). Don't scatter fetch calls through the codebase.
This is what rules 2 to 5 look like together. Here's the module agents produce from them (Node 18+, no SDK):
// lib/email.js (server only)
const API_URL = process.env.EMAIL_API_URL; // your provider's send endpoint
const API_KEY = process.env.EMAIL_API_KEY;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const isRetryable = (status) => status === 429 || status >= 500;
export async function sendEmail(email, { idempotencyKey }) {
for (let attempt = 0; attempt < 4; attempt++) {
let res;
try {
res = await fetch(API_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify(email),
signal: AbortSignal.timeout(10_000),
});
} catch (err) {
// Network error or timeout. Safe to retry because the key is the same.
if (attempt === 3) throw err;
await sleep(1000 * 2 ** attempt);
continue;
}
if (res.ok) return res.json();
const body = await res.json().catch(() => ({}));
if (!isRetryable(res.status) || attempt === 3) {
// Log the provider's stable error name, not just the status code.
throw new Error(`email_failed: ${body.name ?? res.status}`);
}
const retryAfter = Number(res.headers.get('retry-after'));
await sleep(retryAfter ? retryAfter * 1000 : 1000 * 2 ** attempt);
}
}
And a call site:
await sendEmail(
{
from: 'Acme <[email protected]>',
to: user.email,
subject: 'Reset your password',
html,
text,
},
{ idempotencyKey: `password-reset/${user.id}/${token.id}` },
);
When you later change providers, or the provider changes its API, you edit one file.
7. Always send a text version
Keep email copy short and plain, and always include a text version.
Agents love writing HTML emails and forget the text part. Some clients show it, some filters look for it, and it costs one extra field.
8. Test emails go only to you
Send test emails only to my own address. Ask me before sending to anyone else.
An agent that can run code can run your send function. Without this rule, "let me test the welcome email" can mean a welcome email to every row in your seed data. If that seed data was copied from production, those are real people.
I also ask it to finish with the id the API returned. A real id is proof the send worked, not "this should work".
One more for migrations
If the app already sends email with another provider:
Keep the existing function names and call sites, and change only what's inside them. Leave the old provider's code and keys in place until I confirm the new sends work.
Otherwise the agent "cleans up" the old integration in the same pull request, and you have no way back when something breaks.
The prompt
We turned these rules into one copy-paste prompt for Claude Code, Cursor and Codex, with our own API details filled in: cresca.xyz/agents. The rules themselves work with any email API.
What's the rule you'd add? I'm still looking for one that covers how agents should handle email templates.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.