Queue each email in a Postgres outbox in the write's transaction; a worker sends it via an email API with idempotency keys, from a DMARC-aligned subdomain. Suppress bounces via verified webhooks, rate-limit per recipient, and email only hashed, single-use tokens.
Must-have checklist
Must
Publish SPF and DKIM (2048-bit key) for the sending domain so at least one aligns with the From domain, plus DMARC starting at p=none with reports, then quarantine or reject.
Gmail and Yahoo require SPF and DKIM plus DMARC from bulk senders and SPF or DKIM from all; Outlook.com requires all three above 5,000 a day.
Insert an outbox row in the same transaction as the change that triggers the email and send from a worker; never await the provider inside the request.
Provider latency, 429s and outages then never fail sign-up, and no committed change can lose its email.
Give each email a stable dedupe key under a unique constraint (for example receipt:<order_id>) and pass it as the provider idempotency key on every retry where supported.
Resend keeps keys 24 hours; SES SendEmail and Postmark have no key, so the outbox is your only guard against duplicates.
Retry 429, 5xx and network errors with capped backoff and jitter, honouring Retry-After; never retry validation errors, permanent SMTP rejections, or jobs whose token expired.
Retrying a permanent failure repeats it and burns quota, and a reset email that arrives after its link expired only confuses the user.
Verify bounce and complaint webhooks on the raw body (Resend signature, SNS signature plus TopicArn) and store event ids once; Postmark signs nothing, so use basic auth and its IP ranges.
The webhook URL is public; an unverified event could suppress any address or hide real bounces.
Mirror hard bounces and complaints into a Postgres suppression table keyed by normalised address, check it before every send, and record skipped sends.
Repeated sends to dead or complaining addresses raise bounce and spam rates, and providers drop them silently anyway.
Limit emails per recipient address, per account and per IP (for example 3 reset emails per address per hour), plus a daily cap per template, as in the rate-limiting card.
Attackers submit a victim's address to public forms to flood their inbox, burning your quota and reputation.
Return the same response and similar timing for reset and sign-in link requests whether or not the account exists; enqueue the email only for real accounts.
Put only a random, single-use token in links, stored hashed and expiring within 24 hours (shorter for sign-in), on a configured base URL; turn off click tracking for these emails.
NIST caps emailed recovery codes at 24 hours; click tracking routes the token through a third-party redirect and its logs.
Send a plain-text part with every HTML email; give the HTML a lang attribute, real text instead of images of text, alt text, and link text that names the action.
Log template, recipient, provider message id, status and timestamps; never log bodies, links or tokens, and clear outbox payloads once sent or expired.
Use separate provider keys per environment; outside production send through a capture transport or only to allowlisted addresses such as provider test addresses.
A seed script or test run with the production key emails real users and hurts domain reputation.
Should
Send transactional mail from its own subdomain and provider stream, separate from marketing, and keep promotions out of it.
Isolates reputation. Gmail and Yahoo require one-click unsubscribe (RFC 8058) for marketing, not transactional mail; promotions change that.
Alert on rising bounce and complaint rates, and watch the spam rate in Gmail Postmaster Tools (Gmail requires under 0.3% and asks for under 0.1%).
Gmail sends no complaint data to SES, so Gmail users' spam reports never reach those webhooks.
Consume tokens on a POST from a confirm page, or with a typed code, never on the link's GET request.
Some mail security scanners open links before the user does and would use up single-use tokens.
Decisions to make
Asked before building01Do you already have an email provider or relay that you must use?
02How many transactional emails do you expect to send per month in year one?
03Will the same domain also send marketing email or newsletters?
04Do you already run a queue or background job runner?
05Will email carry sign-in links or one-time sign-in codes?
Options
3 comparedEmail API provider called from an outbox worker
Examples, not endorsements: Resend, Postmark, SendGrid
- Most apps, including serverless deployments, because sends are plain HTTPS calls
- You want signed bounce and complaint webhooks and a managed suppression list
- You want provider-side idempotency keys (Resend supports them)
- Volume is high enough that per-email price dominates your bill
- Data-residency rules forbid the provider's regions
- Monthly plans cost more per email than SES at volume
- Webhook formats, signing and idempotency support differ by provider (Postmark has neither keys nor signatures)
Amazon SES through the SESv2 SDK
Examples, not endorsements: Amazon SES
- You already run on AWS and can own IAM, SNS and configuration sets
- High volume where the lowest per-email price matters
- You must launch within days (new accounts start in the sandbox; AWS gives a first answer to production-access requests within 96 hours)
- Nobody on the team will build and watch the bounce and complaint pipeline
- No idempotency token on SendEmail; deduplicate in the outbox
- Bounces and complaints arrive through SNS, which you subscribe to and verify yourself
SMTP relay through Nodemailer
Examples, not endorsements: Nodemailer
- You must use an existing SMTP relay or want to switch providers by changing credentials
- Local development and tests that capture mail instead of sending it
- Short-lived serverless functions, which reconnect on every send and cannot keep a pool
- You need provider idempotency keys or rich event data
- Slower than HTTPS APIs per message; pooling needs a long-running worker
- Bounce and complaint events still come from the relay provider's webhooks, if it has them
Why this approach
Transactional email fails in ways a request handler cannot fix: providers rate-limit, time out and go down, and mailbox providers reject mail from unauthenticated domains. Writing an outbox row in the same transaction as the change and sending from a worker means a slow provider never breaks sign-up, and a retry never sends twice when the provider honours an idempotency key. An email API provider is the default because it adds signed bounce and complaint webhooks, a managed suppression list and an HTTPS API that works from serverless functions. Choose Amazon SES when you already run on AWS and per-email price matters at your volume, and SMTP through Nodemailer when you must use an existing relay.
Lenses
Treat every form that sends email as an abuse target: limit sends per recipient address, per account and per IP, because attackers submit a victim's address to flood their inbox. Return the same response for known and unknown addresses, and enqueue email only for real accounts. Links carry only a random token (for example 32 bytes from crypto.randomBytes), stored as a SHA-256 hash, used once and expiring within NIST's 24-hour cap for emailed recovery codes; sign-in links should expire much sooner. NIST SP 800-63B-4 forbids email for out-of-band authentication, so treat a magic link as a single factor. Build URLs from a configured base URL, never the Host header, and serve token pages with Referrer-Policy: no-referrer before redirecting to a token-free URL. Verify webhooks before acting: Resend signs with svix-* headers, SES events arrive as signed SNS messages, and Postmark signs nothing, so protect it with basic auth and its published IP ranges. Keep provider keys server-only, one per environment, with sending-only permission where offered.
Version notes
emails.send()resolves to{ data, error }without throwing, and the SDK has no retries: throw onerrorin the worker so the job retries.- Pass
{ idempotencyKey }as the second argument (kept 24 hours); a 409invalid_idempotent_requestmeans the payload changed. - The default limit is 10 requests per second per team; on 429 wait the
retry-afterseconds. - Since 6.2.0,
resend.webhooks.verify(...)checks the raw body against thesvix-*headers.
SendEmailhas no idempotency token, and aMessageIdmeans accepted, not sent: deduplicate in the outbox.- The client already retries throttling and 5xx errors (3 attempts by default).
- New accounts start in the sandbox per Region (verified recipients, 200 a day); request production access before launch.
- Needs Node.js 20+. Since 10.2.0,
err.permanentis true for 5xx replies except 503: do not retry those. - Use
jsonTransport: truein development and tests to build messages without sending them.
- Import components and
renderfromreact-email(@react-email/componentsis deprecated);render()returns a Promise. - Build the text part with
toPlainText(html)orrender(element, { plainText: true }).
after()never retries: use it only to nudge the outbox worker. Keep provider keys out ofNEXT_PUBLIC_variables.- Build email links from a configured base URL, never from the request's
hostheader.
Verify checks
When the transaction that creates a user or order rolls back, no outbox row exists; when it commits, exactly one row exists even with the worker stopped.
With the email provider mocked to time out, sign-up and password-reset requests still return their normal response in under 1 second.
Running the same outbox job twice, including from two workers at once, makes one provider call, or several calls that all carry the same idempotency key.
A 429 with Retry-After schedules the next attempt no earlier than that delay, a 5xx retries with backoff, and a validation error or permanent SMTP rejection is not retried and is marked failed.
A bounce webhook with a missing or wrong signature gets 400 and changes nothing; a validly signed payload with unusual JSON whitespace passes.
A verified hard-bounce or complaint event delivered twice adds the address to the suppression table once, and later emails for it are skipped and recorded as suppressed.
Reset requests for an existing and an unknown email return the same status and body with similar timing, and only the existing account gets an outbox row.
An emailed token works once, fails on reuse and after expiry, the database stores only its hash, and no log line contains the raw token.
Opening an emailed link with GET does not consume its token; only the confirming POST does.
Requesting more reset emails for one address than the limit, from many IPs, enqueues no further emails and still returns the same generic response.
Every template renders non-empty HTML and plain-text parts, the HTML root has a lang attribute, and every image has alt text.
With non-production configuration, sending to an address outside the allowlist never calls the real provider.
Common mistakes
- Awaiting the provider call inside the sign-up or reset request, so an outage fails the request.
- Leaving DKIM on the provider's shared domain and SPF on its return path, so neither aligns with the From domain and DMARC fails.
- Retrying with a new idempotency key, or none, so a timeout after acceptance sends duplicates.
- Ignoring bounce and complaint events, so sends keep hitting dead addresses until the provider pauses the account.
- Using the production key in development, or seed scripts that email real users.
- Adding promotions to receipts, which makes them commercial mail.