How to send email from Next.js (App Router) in 5 minutes
Send transactional email from a Next.js Server Action or Route Handler with the Stack Emails SDK — with React Email templates and safe retries.
This tutorial sends a welcome email from a Next.js App Router project using a Server Action. It takes about five minutes.
1. Get an API key and verify a domain
Create a free account, add your domain under Domains and add the DNS records it shows you. Then create an API key under API Keys — a sending access key scoped to that domain is ideal for production.
Add it to .env.local:
STACKEMAILS_API_KEY=se_live_xxxxxxxxxxxx
2. Install the SDK
npm install stackemails
3. Send from a Server Action
Server Actions run only on the server, so your API key never reaches the browser.
// app/actions.ts
"use server";
import { StackEmails } from "stackemails";
const stack = new StackEmails(process.env.STACKEMAILS_API_KEY);
export async function sendWelcome(formData: FormData) {
const email = String(formData.get("email"));
const { id } = await stack.emails.send({
from: "Acme <hello@mail.acme.com>",
to: email,
subject: "Welcome to Acme",
html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
});
return id;
}
The SDK throws a StackEmailsError (with status, code and message) when a request fails, so wrap the call in try/catch if you want to show a friendly error.
4. Use React Email for templates
React Email lets you write emails as components. Install @react-email/render and pass the element as react — the SDK renders it to HTML for you:
import { WelcomeEmail } from "@/emails/welcome";
await stack.emails.send({ from, to, subject: "Welcome", react: <WelcomeEmail name="Ada" /> });
5. Make retries safe
Networks fail. If your action retries after a timeout, you could send the same email twice. Pass an idempotency key derived from the event, and Stack Emails returns the original email instead of sending another:
await stack.emails.send({ ...payload, idempotencyKey: `welcome/${userId}` });
6. Don't block the response
Sending is fast, but you can still keep it off the critical path with after() from next/server, which runs work after the response has streamed:
import { after } from "next/server";
after(() => stack.emails.send(payload));
7. React to delivery events
Add a webhook endpoint under Webhooks to receive email.delivered, email.bounced and other events in a Route Handler. See how to verify webhook signatures.
That's it — you're sending production email from Next.js. The full API is in the docs.
Enjoyed this article?
See more from Stack Emails in Google Search.