To send email from Next.js, run the sending code on the server, never in a client component. In the App Router you have two clean options: a route handler (app/api/send/route.ts) that your form posts to, or a server action (a function marked 'use server') that the form calls directly. Inside either one, connect to an SMTP relay with Nodemailer, or call an HTTP email API with fetch.
This guide shows both entry points, both transports, which runtime each one needs, and the details that cause most production failures: environment variables, serverless timeouts, validation and error handling. For the Node.js fundamentals behind the SMTP code, see Nodemailer SMTP in Node.js.
Choose: route handler or server action
Both run on the server, so the choice is about how your form talks to it. A server action removes the boilerplate of building an endpoint and parsing JSON, and works with progressive enhancement. A route handler gives you a stable URL that can be called from a mobile app, a webhook sender or another service.
| Aspect | Route handler | Server action |
|---|---|---|
| Entry point | HTTP POST to /api/send | Function passed to a form action or called from an event handler |
| Good for | Public endpoints, non-React callers, webhooks | Forms inside your own Next.js app |
| Input | request.json() or request.formData() | FormData argument |
| Response | Response or NextResponse with a status code | Returned object, usually used with useActionState |
| Abuse surface | Reachable by anyone who knows the URL | Also reachable as a POST endpoint; treat it as public |
Treat both as public. A server action is compiled to an endpoint, so authentication, validation and rate limiting are your responsibility in either case.
Store credentials in environment variables
Put SMTP or API credentials in .env.local for development and in your host's secret store for production. Do not prefix them with NEXT_PUBLIC_, because that prefix inlines the value into the browser bundle. Only read them inside server code.
# .env.local (do not commit this file)
SMTP_HOST=smtp.migosmtp.com
SMTP_PORT=587
SMTP_USER=your-smtp-username
SMTP_PASS=your-smtp-password
MAIL_FROM="Acme Support <[email protected]>"
[email protected]The From address must use a domain you have authenticated with SPF, DKIM and DMARC, otherwise receivers may reject or junk the message. See authenticating your sending domain.
Send over SMTP with Nodemailer in a route handler
Install the package with npm install nodemailer (add @types/nodemailer for TypeScript). Nodemailer opens raw TCP sockets, so the route must run on the Node.js runtime, not the Edge runtime. Declare it explicitly.
// app/api/send/route.ts
import nodemailer from 'nodemailer';
export const runtime = 'nodejs';
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 587),
secure: Number(process.env.SMTP_PORT) === 465, // true = implicit TLS
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
export async function POST(req: Request) {
const { name, email, message } = await req.json();
if (!name || !email || !message || !/^[^@\s]+@[^@\s]+$/.test(email)) {
return Response.json({ error: 'Invalid input' }, { status: 400 });
}
try {
const info = await transporter.sendMail({
from: process.env.MAIL_FROM,
to: process.env.MAIL_TO,
replyTo: email,
subject: 'New contact form message',
text: `From: ${name} <${email}>\n\n${message}`,
});
return Response.json({ id: info.messageId });
} catch (err) {
console.error('mail failed', err);
return Response.json({ error: 'Could not send' }, { status: 502 });
}
}Two details matter here. The visitor's address goes in replyTo, never in from, so you keep sending from your own authenticated domain. And the transporter is created at module level so a warm server instance reuses it. For port and TLS background, see choosing between ports 25, 465 and 587.
Send from a server action
A server action does the same work without a route file. Put the function in its own file marked with 'use server' and import it into a form.
// app/contact/actions.ts
'use server';
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 587),
secure: Number(process.env.SMTP_PORT) === 465,
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
export async function sendContact(prev: unknown, formData: FormData) {
const name = String(formData.get('name') || '').trim();
const email = String(formData.get('email') || '').trim();
const message = String(formData.get('message') || '').trim();
if (!name || !email || !message) return { ok: false, error: 'All fields are required' };
try {
await transporter.sendMail({
from: process.env.MAIL_FROM,
to: process.env.MAIL_TO,
replyTo: email,
subject: 'New contact form message',
text: message,
});
return { ok: true };
} catch (e) {
return { ok: false, error: 'Could not send, please try again' };
}
}// app/contact/form.tsx
'use client';
import { useActionState } from 'react';
import { sendContact } from './actions';
export default function ContactForm() {
const [state, action, pending] = useActionState(sendContact, null);
return (
<form action={action}>
<input name="name" required />
<input name="email" type="email" required />
<textarea name="message" required />
<button disabled={pending}>Send</button>
{state?.error && <p role="alert">{state.error}</p>}
</form>
);
}useActionState is available in React 19, which current Next.js App Router versions use. On older setups it was named useFormState; check the Next.js documentation for your version.
Send over an HTTP email API instead
If you deploy to the Edge runtime, or to a host that restricts outbound SMTP connections, use an HTTPS API call. It works anywhere fetch works and avoids socket and port issues. The request is a POST with a Bearer key. The payload field names below are illustrative: confirm the exact schema in the API reference before use.
// app/api/send-api/route.ts
export async function POST(req: Request) {
const { email, message } = await req.json();
const res = await fetch('https://api.migosmtp.com/v1/send', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MAIL_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: process.env.MAIL_FROM,
to: process.env.MAIL_TO,
reply_to: email,
subject: 'New contact form message',
text: message,
}),
});
if (!res.ok) {
return Response.json({ error: 'Provider rejected the request' }, { status: 502 });
}
return Response.json({ ok: true });
}For a comparison of the two approaches, see SMTP versus API.
HTML bodies, plain-text fallbacks and attachments
Most real messages need an HTML body. Send both an html and a text part: mail clients that cannot render HTML, and spam filters that compare the two versions, both benefit from a matching plain-text alternative. Keep the two versions equivalent in content. Nodemailer builds the multipart structure for you; if you want to understand what is on the wire, see multipart MIME explained.
Attachments go in the attachments array as objects with a filename and content. Accept uploads carefully: limit the size, check the type on the server and do not attach files the visitor can point at by path. Remember that SMTP is not a file transfer system, so keep totals well below the limits in email size limits. For anything large, send a link instead.
Test it before you deploy
- Run
npm run devand submit the form with a recipient you control. - Check the server console for the Nodemailer
messageId. If the call throws, read the full error: the response code and message from the relay tell you exactly what went wrong. - Open the received message and view the original headers. Confirm that SPF and DKIM show as passing and that the From domain aligns. See reading email headers.
- Switch the environment to production values on your host and repeat the test from the deployed URL, because the runtime and outbound network rules are different from your laptop.
- Send a message to an address that does not exist and confirm your application logs or webhooks record the bounce.
If you need to see the raw SMTP conversation while debugging, a command-line test against the relay is faster than redeploying; testing an SMTP connection covers the tools.
Production concerns
- Serverless timeouts. A function that waits on a slow SMTP handshake can hit its time limit. Set a connection timeout in Nodemailer (
connectionTimeout,socketTimeout) and return a clear error. - Do not block the user on retries. For anything beyond a contact form, enqueue the message and retry in a worker. See reliable sending queues.
- Validate and sanitise. Reject newlines in any value that ends up in a header such as the subject or reply-to. See header injection.
- Rate limit. An open form endpoint will be found by bots. Add a per-IP limit and a honeypot field or a CAPTCHA.
- Never trust the client for the recipient. Take the destination address from server configuration, not from the request body.
- Use bounce and complaint events. A successful send call only means the relay accepted the message. Delivery results arrive later; see delivery event webhooks.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Module not found: net, tls or dns | Route compiled for the Edge runtime | Add export const runtime = "nodejs" or switch to the HTTP API |
| Env var is undefined at runtime | Variable missing in the host, or read in client code | Set it in the host dashboard and read it only on the server |
| 535 authentication failed | Wrong username or password, or credentials for another service | Re-check credentials. See fixing 535 errors |
| ETIMEDOUT or ECONNREFUSED | Host blocks outbound SMTP ports or wrong port | Try 587 or 465, or use the HTTP API |
| Wrong version number or SSL error | secure set to true on port 587 | Use secure false with 587 (STARTTLS) and true with 465 |
| Message accepted but lands in spam | Unauthenticated From domain | Fix SPF, DKIM and DMARC. See spam troubleshooting |
When to use which, and next steps
Use a server action for forms inside your own app, a route handler for anything callable from outside, SMTP when you want one configuration that works across languages and tools, and the HTTP API when you run on Edge or want structured responses. Whichever you choose, test with a staging address first; see testing email in staging, then add webhook handling so bounces and complaints are acted on.
Send from your Next.js app Point Nodemailer at the MigoSMTP relay or call the email API with a Bearer key.
References and further reading
Frequently asked questions
Can I send email directly from a Next.js client component?
No. Client code runs in the browser and would expose your credentials. Send from a route handler or server action.
Does Nodemailer work on the Edge runtime?
No. Nodemailer needs Node.js sockets, so use the Node.js runtime or call an HTTP email API with fetch.
Which port should I use for SMTP in Next.js?
Use 587 with STARTTLS (secure false in Nodemailer) or 465 with implicit TLS (secure true). Avoid port 25 from hosting platforms.
Should I use a route handler or a server action?
Use a server action for forms inside your app and a route handler when other callers need a stable URL. Validate and rate limit both.
Why do my emails send locally but fail on Vercel or another host?
Usually missing environment variables, the wrong runtime, or the host blocking outbound SMTP ports. Check logs and try the HTTP API.