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

Send Email from Next.js: API Routes, Server Actions and SMTP

How to send email from a Next.js App Router project using a route handler or a server action, over SMTP with Nodemailer or over an HTTP email API, with environment variables, runtime choice, validation and error handling.

AM
Written by Aarav Mehta
Head of Deliverability
Reviewed by Sana Qureshi
  • Published26 May 2024
  • Read time8 min
  • Length1,697 words
Share this guide

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.

Where to send fromRoute handler or server action, always on the server
SMTP transportNodemailer on the Node.js runtime, port 587 with STARTTLS or 465 with implicit TLS
HTTP transportfetch to an email API with a Bearer key; works on the Edge runtime too
SecretsPlain environment variables, never prefixed with NEXT_PUBLIC_

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.

AspectRoute handlerServer action
Entry pointHTTP POST to /api/sendFunction passed to a form action or called from an event handler
Good forPublic endpoints, non-React callers, webhooksForms inside your own Next.js app
Inputrequest.json() or request.formData()FormData argument
ResponseResponse or NextResponse with a status codeReturned object, usually used with useActionState
Abuse surfaceReachable by anyone who knows the URLAlso 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

  1. Run npm run dev and submit the form with a recipient you control.
  2. 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.
  3. 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.
  4. 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.
  5. 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

SymptomLikely causeFix
Module not found: net, tls or dnsRoute compiled for the Edge runtimeAdd export const runtime = "nodejs" or switch to the HTTP API
Env var is undefined at runtimeVariable missing in the host, or read in client codeSet it in the host dashboard and read it only on the server
535 authentication failedWrong username or password, or credentials for another serviceRe-check credentials. See fixing 535 errors
ETIMEDOUT or ECONNREFUSEDHost blocks outbound SMTP ports or wrong portTry 587 or 465, or use the HTTP API
Wrong version number or SSL errorsecure set to true on port 587Use secure false with 587 (STARTTLS) and true with 465
Message accepted but lands in spamUnauthenticated From domainFix 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.

Explore the SMTP relay

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.

Topics#next.js#nodemailer#server actions#route handler#smtp#javascript
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