To send email from Next.js, run the send on the server: in a route handler under app/api/, or in a server action marked 'use server'. From there you either call an email API with fetch, or speak SMTP with Nodemailer. The examples below use the App Router, which is the default for new Next.js projects.
Keep the key on the server
Put the key in .env.local during development and in your host’s environment settings in production:
MAILCANDOR_KEY=mc_live_xxxxxxxxxxxxxxxx
Do not prefix it with NEXT_PUBLIC_. Next.js inlines NEXT_PUBLIC_ variables into the JavaScript it sends to the browser, so a prefixed key is a public key. Without the prefix, process.env.MAILCANDOR_KEY is only readable in server code.
Option 1: fetch and an email API
In a route handler
A route handler is a file named route.ts that exports a function per HTTP method. This one accepts a JSON body and sends one email:
// app/api/send/route.ts
export async function POST(request: Request) {
const { email, name } = await request.json();
if (typeof email !== 'string' || !email.includes('@')) {
return Response.json({ error: 'A valid email is required' }, { status: 400 });
}
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MAILCANDOR_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: 'Acme <hello@acme.com>',
to: email,
subject: 'Welcome to Acme',
text: `Hi ${name ?? 'there'}, thanks for signing up.`,
}),
});
if (!res.ok) {
const { error } = await res.json();
console.error('Email failed', error);
return Response.json({ error: 'Could not send email' }, { status: 502 });
}
const { id } = await res.json();
return Response.json({ id });
}
Call it from anywhere with fetch('/api/send', { method: 'POST', body: JSON.stringify({ email, name }) }). The API returns 202 with an id as soon as the email is queued; the handler does not wait for delivery.
In a server action (contact form)
For a form inside your app, a server action skips the route handler entirely. The form posts straight to a function that runs on the server:
// app/contact/actions.ts
'use server';
export async function sendMessage(formData: FormData) {
const email = String(formData.get('email') ?? '');
const message = String(formData.get('message') ?? '');
if (!email.includes('@') || message.length < 2) {
throw new Error('Please enter your email and a message');
}
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MAILCANDOR_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: 'Contact form <forms@acme.com>',
to: 'team@acme.com',
reply_to: email,
subject: `New message from ${email}`,
text: message,
}),
});
if (!res.ok) throw new Error('Could not send your message');
}
// app/contact/page.tsx
import { sendMessage } from './actions';
export default function ContactPage() {
return (
<form action={sendMessage}>
<input name="email" type="email" required />
<textarea name="message" required />
<button type="submit">Send</button>
</form>
);
}
Three details matter in a contact form:
- The visitor’s address goes in
reply_to, notfrom. You can only send from a domain you have verified. Pressing reply in your inbox still answers the visitor. - Send user input as
text. If you buildhtmlfrom form input, escape it first, or a visitor can inject links and markup into your inbox. - Rate limit the action. Any public form that sends email will be found by bots. A honeypot field and a per-IP limit stop most of them.
If you want to show a success or error message without a page reload, wrap the action with React’s useActionState in a client component and return a status object instead of throwing.
Option 2: Nodemailer over SMTP
If you already have Nodemailer code, it works in Next.js on the Node.js runtime. Create the transport once in a server-only module so it is reused across requests:
// lib/mailer.ts
import 'server-only';
import nodemailer from 'nodemailer';
export const mailer = nodemailer.createTransport({
host: 'smtp.mailcandor.com',
port: 465,
secure: true,
auth: { user: 'mailcandor', pass: process.env.MAILCANDOR_KEY },
});
// app/api/send/route.ts
import { mailer } from '@/lib/mailer';
export async function POST(request: Request) {
const { email } = await request.json();
await mailer.sendMail({
from: 'Acme <hello@acme.com>',
to: email,
subject: 'Welcome to Acme',
text: 'Thanks for signing up.',
});
return Response.json({ ok: true });
}
The server-only package (install it with npm install server-only) makes the build fail if a client component ever imports this file. Do not set export const runtime = 'edge' on routes that use Nodemailer: the Edge runtime has no TCP sockets, so SMTP cannot connect. The Nodemailer SMTP guide covers ports, pooling and attachments in more depth.
Rendering email templates
Writing HTML email by hand is slow. Many Next.js projects build templates as React components with React Email, render them to an HTML string on the server, and send the string. The React Email guide shows the full flow.
Which should you choose?
| Email API (fetch) | Nodemailer (SMTP) | |
|---|---|---|
| Extra packages | None | nodemailer |
| Edge runtime | Works | Does not work |
| Serverless cold starts | One HTTPS request | SMTP handshake on each new instance |
| Delivery events | Webhooks with the email id | Usually none |
| Best for | New Next.js apps, Vercel and other serverless hosts | Existing Nodemailer code you want to keep |
On serverless hosts, each function instance opens its own SMTP connection, which adds a handshake to cold requests. An HTTP API call has no such setup, so it is the better default for Next.js.
Before you send: verify your domain
Whichever option you pick, email from a domain without SPF, DKIM and DMARC records is likely to land in spam or be rejected. Add your domain in your email provider’s dashboard, publish the DNS records it gives you, and wait for them to verify. The SPF, DKIM and DMARC guide explains what each record does.