New guide: how to warm up a dedicated IP without hurting your reputation. Read now →
Log in
MigoSMTP
SMTP and APIUpdated 26 Oct 2026

Next.js Send Email with SMTP: Route Handlers, Server Actions and Nodemailer

Send email from a Next.js App Router project through SMTP: route handler and server action examples with Nodemailer, Node.js runtime, validation, abuse protection, environment variables and serverless pitfalls.

KM
Written by Karan Malhotra
API and Developer Experience Lead
Reviewed by Ethan Brooks
  • Published14 Jul 2026
  • Read time8 min
  • Length1,607 words
Share this guide

Next.js has no email feature of its own. You send mail from server code: a route handler, a server action or a background job, using an SMTP client or an HTTP email API. The framework adds a few things that catch people out: code can run on the Node.js runtime or the edge runtime, and SMTP libraries only work on the first; server and client code live in the same project, so secrets can leak into the browser bundle if you are careless; serverless hosting freezes or kills a function the moment a response is returned, which loses mail that you try to send "in the background"; and public forms attract abuse. This guide shows how to send through SMTP from the App Router with Nodemailer, as a route handler and as a server action, and how to deal with each of these points. The examples use placeholders; take real values from your SMTP provider's dashboard. For the Nodemailer basics, see our Nodemailer guide.

RuntimeNodemailer needs the Node.js runtime, not edge
WhereRoute handler or server action, never client code
SecretsServer-only environment variables, no NEXT_PUBLIC_ prefix
CareValidate, rate-limit and await the send before responding

Install and configure

npm install nodemailer
npm install -D @types/nodemailer

Put the connection details in .env.local for development, and in your hosting provider's environment settings for production. Do not prefix them with NEXT_PUBLIC_: that prefix tells Next.js to inline the value into the JavaScript sent to browsers, which would publish your SMTP password.

# .env.local  (never commit this file)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-smtp-user
SMTP_PASSWORD=your-smtp-password
MAIL_FROM="Example App <[email protected]>"
[email protected]

Create a reusable mailer

Put the transport in one server-only module. The server-only package makes the build fail if a client component imports the file by mistake.

// lib/mailer.ts
import "server-only";
import nodemailer from "nodemailer";

const port = Number(process.env.SMTP_PORT ?? 587);

export const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port,
  secure: port === 465,          // implicit TLS on 465, STARTTLS otherwise
  requireTLS: port !== 465,      // refuse to send the password without TLS
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASSWORD,
  },
  connectionTimeout: 10_000,
  greetingTimeout: 10_000,
  socketTimeout: 20_000,
});

The secure flag in Nodemailer means implicit TLS, which is what port 465 uses. For port 587 you leave it false and Nodemailer upgrades the connection with STARTTLS; requireTLS makes it fail if the upgrade is not possible. The three timeouts stop a blocked port from holding a function open until the platform kills it. If you are not sure about the port, read which SMTP port to use.

Send from a route handler

A route handler in the App Router is a file named route.ts. Declare the runtime explicitly so the file is never moved to the edge, validate the input and await the send before returning a response.

// app/api/contact/route.ts
import { NextResponse } from "next/server";
import { transporter } from "@/lib/mailer";

export const runtime = "nodejs";

const isEmail = (v: unknown): v is string =>
  typeof v === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) && v.length <= 254;

export async function POST(req: Request) {
  const body = await req.json().catch(() => null);
  if (!body || !isEmail(body.email) ||
      typeof body.message !== "string" || body.message.length > 5000) {
    return NextResponse.json({ error: "Invalid input" }, { status: 422 });
  }
  if (body.website) {                       // honeypot field, must stay empty
    return NextResponse.json({ ok: true });
  }

  try {
    await transporter.sendMail({
      from: process.env.MAIL_FROM,
      to: process.env.MAIL_TO,
      replyTo: body.email,
      subject: "New contact form message",
      text: `From: ${body.email}\n\n${body.message}`,
    });
    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("mail failed", (err as Error).message);
    return NextResponse.json({ error: "Could not send" }, { status: 502 });
  }
}

Three details are deliberate. The visitor's address goes into replyTo, never into from: sending as an address you do not control fails authentication checks and looks like spoofing. Your own authenticated address is the sender. Second, the user's text is placed in the plain-text body, not interpolated into HTML; if you build an HTML version, escape it. Third, the handler logs the error message but not the credentials or the full request.

Send from a server action

If the form lives in a React Server Components app, a server action avoids writing an API route. Mark the file with "use server" and call the same mailer. Treat the action as a public endpoint, because anyone can call it directly with any arguments; validate again on the server even if the form validates in the browser.

// app/contact/actions.ts
"use server";
import { transporter } from "@/lib/mailer";

export async function sendContact(prev: unknown, formData: FormData) {
  const email = String(formData.get("email") ?? "");
  const message = String(formData.get("message") ?? "");
  if (formData.get("website")) return { ok: true };       // honeypot
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || message.length < 5 || message.length > 5000) {
    return { ok: false, error: "Please check your details." };
  }
  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 {
    return { ok: false, error: "We could not send your message. Try again later." };
  }
}

Use the action with useActionState in a client form component, so the page can show a pending state and the result without a full reload.

Serverless: always await the send

On serverless platforms, the function may be frozen or terminated as soon as the response is returned. If you start transporter.sendMail() without awaiting it and return immediately, the message may never leave. Await the send, or hand the work to a durable queue or background job service. If the send must not delay the response, enqueue a job that a separate worker processes, and make the job safe to retry using the approach in rate limits, retries and backoff. Also expect a cold start: the first request after idle time spends extra time starting, so keep timeouts generous enough but not unlimited.

Connection reuse behaves differently too. In a long-running Node server, a single module-level transporter is reused. In serverless, each instance has its own, and many instances running at once can open many simultaneous connections to your SMTP server, which may exceed its connection limit. If you send a lot, prefer an HTTP email API or a queue with a small number of workers.

Protect public forms from abuse

An unprotected contact endpoint is a target. Bots will submit it thousands of times, and every submission sends an email from your domain. Combine several measures: a honeypot field that real users never fill; a rate limit per IP address or per session using a store that is shared across instances, such as a key-value service; a CAPTCHA or token challenge verified on the server; strict length limits; and rejection of any value containing line breaks that you place in a header or subject. Do not allow users to choose the recipient. Validate addresses before you send with the checks described in email validation before sending.

Build HTML emails

For anything other than a plain internal notification, send HTML with a plain-text alternative. You can render templates written as React components to an HTML string on the server, or use template literals with careful escaping. Whatever tool you choose, use inline styles and simple table-based layouts, since many email clients ignore external CSS and modern layout features. The HTML email template guide lists what renders reliably, and the text part should say the same thing as the HTML part.

Pre-deployment checklist

Before you ship, walk through a short list. Confirm that every variable exists in each environment, including preview deployments, because a missing value is the most common reason that mail works locally and fails online. Send a test message from the deployed environment, not only from your laptop, and look at the headers of the received message to confirm the From domain passes SPF, DKIM and DMARC. Check that the route handler returns useful status codes: 422 for bad input, 429 when a visitor is rate-limited and 502 when the mail server fails, so your front end can show the right message. Make sure errors are logged to a service you actually monitor, with the SMTP reply code but without credentials, and set an alert for repeated failures. Finally, decide what happens to a message when sending fails: show an apology and an alternative contact route, or store the submission so that you can follow up. Losing a customer enquiry silently is worse than showing an error.

Common errors and fixes

SymptomLikely causeFix
Build error about Node modules when using NodemailerThe file runs on the edge runtimeAdd export const runtime = "nodejs"
Invalid login: 535Wrong credentials or variables not set in productionCheck the hosting environment and re-copy; see SMTP error 535
ETIMEDOUT or ECONNREFUSEDWrong host or port, or outbound SMTP blocked by the platformTest the port from the platform; consider an HTTP email API
wrong version numbersecure flag does not match the portUse secure: true with 465 and false with 587
Works locally, nothing in productionMissing environment variables, or the send is not awaitedSet variables and await sendMail
SMTP password visible in browser codeVariable prefixed with NEXT_PUBLIC_Rename it, rotate the password and redeploy
Messages accepted but in spamMissing SPF, DKIM or DMARCFollow the domain authentication guide

To confirm the credentials independently of your application, use the steps in how to test an SMTP connection. If it works there and fails in your deployment, the difference is the environment or the network.

Send from Next.js through a managed relay Use the SMTP host and credentials from your dashboard, or use the email API when your platform blocks SMTP.

Explore the email API

References and further reading

Frequently asked questions

Can I use Nodemailer on the Next.js edge runtime?

No. Nodemailer needs Node.js APIs. Set export const runtime = "nodejs" in the route handler, or use an HTTP email API from the edge.

Where should SMTP credentials go in Next.js?

In server-only environment variables set in .env.local for development and in your hosting settings for production. Never prefix them with NEXT_PUBLIC_.

Why does my email not send on Vercel or other serverless hosts?

The function may be stopped after the response. Await sendMail before returning, or use a queue. Some platforms also block outbound SMTP ports; use an HTTP email API if so.

Should I send from the visitor address in a contact form?

No. Send from your own authenticated address and put the visitor address in replyTo, otherwise the message fails authentication checks.

How do I stop bots abusing my Next.js contact form?

Combine a honeypot, server-side validation, a shared rate limit, a CAPTCHA or token check and strict length limits.

Topics#nextjs#node.js#nodemailer#smtp#javascript#developers
Was this guide helpful?Your answer helps us improve our documentation.

Start sending in minutes.

Create an account, add your domain and send your first email.

Get started Talk to sales