Frameworks

How to send email from Next.js

Short answer

To send email from Next.js, call an email API with fetch from a route handler (app/api/send/route.ts) or a server action marked 'use server'. Keep the API key in a server-only environment variable without the NEXT_PUBLIC_ prefix. Nodemailer over SMTP also works, but only in the Node.js runtime, not the Edge runtime. Verify your sending domain with SPF, DKIM and DMARC first.

Last checked 16 November 2026

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, not from. 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 build html from 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.

Questions

Can I send email from a Next.js client component?

No. Sending needs a secret key, and anything in a client component ships to the browser. Send from a route handler or a server action, which run only on the server.

Does Nodemailer work in Next.js?

Yes, in route handlers and server actions on the Node.js runtime, which is the default. It does not work on the Edge runtime, because SMTP needs raw TCP sockets. An HTTP email API works on both.

Should I use a route handler or a server action for a contact form?

A server action is less code for a form inside your Next.js app. Use a route handler when something outside the app, such as a mobile app or a webhook, needs to trigger the email.

How do I stop spam through my Next.js contact form?

Validate the input on the server, rate limit the endpoint, add a honeypot field or a CAPTCHA, and send to your own inbox with the visitor's address in reply_to rather than in from.

Where do I put the API key in Next.js?

In .env.local for development and in your host's environment settings for production. Do not prefix it with NEXT_PUBLIC_, or Next.js will bundle it into client code.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.