Send Transactional Email
Welcome emails and payment receipts that land in the inbox, not spam. One small email module handles every send.
Every product sends the same handful of emails: welcome, here’s your receipt, your password reset link. Each one goes to one person because of something they just did. That’s transactional email, and it’s different from newsletters: it has to arrive in seconds, land in the inbox, and never send twice.
The easy way is to call the email API inline wherever you need it, which gets messy by the
third email. This guide sets up a small module instead, with templates in one place, one sendEmail() everything calls, and a verified
domain so you reach real people. Then it wires it to the two moments that matter: signup
and payment.
We use Resend for sending (free tier: 3,000 emails/month) inside an Astro project.
What you’ll have at the end
- A verified sending domain (SPF + DKIM), so mail comes from
hello@yourdomain.com. src/lib/email.ts: one function that sends, logs failures, and never throws at callers.- Two templates (welcome + receipt), each with HTML and plain-text versions.
- A receipt sent from your Stripe webhook that can’t double-send on retries.
- A way to test bounces and spam complaints without hurting your sender reputation.
Before you start
- An Astro project with a server adapter (
npm create astro@latest, thennpx astro add node). - A free Resend account → https://resend.com, and an API key (starts with
re_). - A domain you can add DNS records to. Required to email anyone but yourself.
Step 1: Install and add the key
npm install resend
In .env (confirm it’s gitignored):
RESEND_API_KEY=re_your_key
EMAIL_FROM="Your App <hello@yourdomain.com>"
No
PUBLIC_prefix. Astro shipsPUBLIC_*variables to the browser. Anyone with this key can send mail as you.
Step 2: Verify your domain (do this first, it takes a while)
Resend → Domains → Add Domain. Use a subdomain like mail.yourdomain.com or the root;
either works. Resend shows 3–4 DNS records. Add them at your DNS provider exactly as shown:
| Record | Type | What it proves |
|---|---|---|
resend._domainkey | TXT | DKIM: the mail was signed by you and not altered |
send (MX + TXT) | MX / TXT | SPF: Resend’s servers may send for this domain |
Then add one record Resend doesn’t require but inbox providers increasingly do:
_dmarc.yourdomain.com TXT "v=DMARC1; p=none; rua=mailto:you@yourdomain.com"
p=none means “watch, don’t block”, which is safe to start with. Click Verify in Resend.
DNS can take minutes to a few hours.
Gotcha: if you’re on Cloudflare DNS, set these records to DNS only (grey cloud), not proxied. Proxied TXT/MX records don’t resolve the way mail servers expect.
Gotcha: until the domain shows Verified, Resend only delivers to your own account email. Code that “works” in testing silently goes nowhere for real users.
Step 3: One module that does all sending
Create src/lib/email.ts:
import { Resend } from "resend";
const resend = new Resend(import.meta.env.RESEND_API_KEY);
const FROM = import.meta.env.EMAIL_FROM;
export type Email = { subject: string; html: string; text: string };
/**
* Send one email. Returns true/false and never throws, so a mail outage can't
* break signup or checkout. Pass an idempotencyKey for anything that might be
* retried (webhooks!) so the same email is never sent twice.
*/
export async function sendEmail(
to: string,
email: Email,
opts: { idempotencyKey?: string } = {},
): Promise<boolean> {
const { data, error } = await resend.emails.send(
{ from: FROM, to, subject: email.subject, html: email.html, text: email.text },
opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,
);
if (error) {
console.error("email failed:", { to, subject: email.subject, error });
return false;
}
console.log("email sent:", data?.id);
return true;
}
Gotcha: the Resend SDK returns
{ data, error }. It does not throw on API errors like a bad key or unverified domain. A baretry/catcharoundsend()catches almost nothing. Always checkerror.
Step 4: Templates as plain functions
No template engine needed. A template is a function that takes data and returns subject,
HTML, and text. Create src/lib/templates.ts:
import type { Email } from "./email";
// Anything a user typed (their name!) goes through this before entering HTML.
const esc = (s: string) =>
s.replace(/[&<>"']/g, (c) =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!,
);
const layout = (body: string) => `<!doctype html>
<html><body style="margin:0;padding:24px;background:#f6f6f6;font-family:system-ui,sans-serif">
<div style="max-width:520px;margin:0 auto;background:#fff;padding:32px;border-radius:8px;color:#18181b;line-height:1.5">
${body}
</div>
</body></html>`;
export function welcomeEmail(name: string, appUrl: string): Email {
const n = esc(name || "there");
return {
subject: "Welcome! Here's how to get started",
html: layout(`
<h1 style="font-size:20px;margin:0 0 12px">Welcome, ${n}.</h1>
<p>Your account is ready. The fastest way to see what it does:</p>
<p><a href="${appUrl}" style="display:inline-block;background:#18181b;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Open the app</a></p>
<p style="color:#57606a;font-size:14px">Reply to this email if you get stuck. A human reads it.</p>`),
text: `Welcome, ${name || "there"}.\n\nYour account is ready: ${appUrl}\n\nReply if you get stuck. A human reads it.`,
};
}
export function receiptEmail(opts: {
amount: number; // in the smallest unit, e.g. cents, straight from Stripe
currency: string;
product: string;
receiptId: string;
}): Email {
const price = new Intl.NumberFormat("en", {
style: "currency",
currency: opts.currency.toUpperCase(),
}).format(opts.amount / 100);
const product = esc(opts.product);
return {
subject: `Receipt for ${opts.product}`,
html: layout(`
<h1 style="font-size:20px;margin:0 0 12px">Thanks for your purchase.</h1>
<table style="width:100%;border-collapse:collapse;margin:16px 0">
<tr><td style="padding:8px 0;border-bottom:1px solid #eee">${product}</td>
<td style="padding:8px 0;border-bottom:1px solid #eee;text-align:right"><strong>${price}</strong></td></tr>
</table>
<p style="color:#57606a;font-size:14px">Receipt ID: ${esc(opts.receiptId)}</p>`),
text: `Thanks for your purchase.\n\n${opts.product}: ${price}\nReceipt ID: ${opts.receiptId}`,
};
}
Two rules for email HTML:
- Always send a
textversion. Some clients show it, spam filters like seeing it, and it’s your fallback when HTML renders badly. - Inline styles only, tables for layout. Email clients ignore
<style>blocks and most modern CSS. Ugly, but it renders everywhere.
Divide by 100 only for two-decimal currencies. Stripe amounts are in the smallest unit; for zero-decimal currencies like JPY,
amountis already whole yen.
Step 5: Send the welcome email on signup
Wherever a user is created (your signup endpoint, or right after the auth callback in Add Authentication), call it once:
import { sendEmail } from "../../lib/email";
import { welcomeEmail } from "../../lib/templates";
// ...after the user row is created successfully:
await sendEmail(user.email, welcomeEmail(user.name, "https://yourdomain.com/app"), {
idempotencyKey: `welcome/${user.id}`,
});
The key welcome/<user id> means even if this code path runs twice for the same user, they
get one welcome email.
Step 6: Send the receipt from the Stripe webhook
In Take Payments, the webhook is the only trustworthy “they paid” signal, so that’s
where the receipt goes. Inside the checkout.session.completed branch of
src/pages/api/stripe-webhook.ts:
import { sendEmail } from "../../lib/email";
import { receiptEmail } from "../../lib/templates";
if (event.type === "checkout.session.completed") {
const session = event.data.object as Stripe.Checkout.Session;
const to = session.customer_details?.email;
// ...mark the order paid first, then:
if (to && session.amount_total != null) {
await sendEmail(
to,
receiptEmail({
amount: session.amount_total,
currency: session.currency ?? "usd",
product: "Pro plan",
receiptId: session.id,
}),
{ idempotencyKey: `receipt/${event.id}` },
);
}
}
Why the idempotency key matters here: Stripe retries webhooks if your endpoint is slow or errors, and sometimes the same event arrives three times. Keying on
event.idmakes Resend drop the duplicates, so a customer never gets three receipts for one payment.
Gotcha: don’t let a failed email fail the webhook.
sendEmailreturnsfalseinstead of throwing, so the webhook still returns 200 and Stripe doesn’t retry a payment that already succeeded.
Step 7: Test without wrecking your reputation
Resend provides test addresses that simulate outcomes without real delivery:
| Send to | Simulates |
|---|---|
delivered@resend.dev | a normal successful delivery |
bounced@resend.dev | a hard bounce (address doesn’t exist) |
complained@resend.dev | the recipient marking it as spam |
Use these in tests and dev, never fake addresses like test@example.com. Real bounces
against made-up addresses count against your domain.
Then send yourself the real thing and check it in Gmail: open the message → ⋮ → Show original. You want to see SPF: PASS, DKIM: PASS, DMARC: PASS. All three green means you’re set up correctly.
You now have
A verified domain, one safe sendEmail() the whole app shares, welcome and receipt
templates with text fallbacks, and receipts that can’t double-send. Next time you need an
email, it’s one new template function.
Troubleshooting
- Emails “send” but never arrive → domain not verified yet; Resend only delivers to your own account email until it is. Check Domains shows Verified.
- Landing in spam → confirm SPF/DKIM/DMARC all PASS in “Show original”. Also: don’t send from a brand-new domain at volume on day one, and avoid all-image emails.
- Error says
fromaddress not allowed →EMAIL_FROMmust use the exact domain (or subdomain) you verified. - Customer got duplicate receipts → you’re missing the
idempotencyKey, or keying it on something that changes between retries. Useevent.id. - Works locally, nothing sends in production →
RESEND_API_KEY/EMAIL_FROMaren’t set in your host’s environment variables.