Nodemailer is the standard Node.js library for sending email over SMTP. You create a transport with your SMTP server’s host, port and credentials, then call sendMail() with the message. The settings that trip people up are the port and the secure flag; the rest is straightforward.
A working SMTP transport
npm install nodemailer
import nodemailer from 'nodemailer';
const transport = nodemailer.createTransport({
host: 'smtp.mailcandor.com',
port: 465,
secure: true,
auth: {
user: 'mailcandor',
pass: process.env.MAILCANDOR_KEY,
},
});
const info = await transport.sendMail({
from: 'Acme <hello@acme.com>',
to: 'sam@example.com',
subject: 'Your receipt',
text: 'Thanks for your order.',
html: '<p>Thanks for your order.</p>',
});
console.log(info.messageId);
The example uses Mailcandor’s SMTP relay, where the username is always mailcandor and the password is your API key. Any SMTP provider works the same way with its own host and credentials.
Port 465 or 587: getting secure right
| Port | secure |
What happens |
|---|---|---|
| 465 | true |
TLS from the first byte (implicit TLS) |
| 587 | false |
Plain connection that upgrades with STARTTLS |
| 25 | false |
Server-to-server relay; often blocked by cloud hosts |
secure: false does not mean unencrypted. On port 587 Nodemailer sees the server offer STARTTLS and upgrades the connection before it sends your password. To refuse to continue if the upgrade does not happen, add requireTLS: true.
The most common error is a mismatch: secure: true on port 587 or secure: false on port 465 both fail, usually with a timeout or a “wrong version number” TLS error. RFC 8314 recommends implicit TLS on 465 for message submission. Our SMTP ports guide covers the history.
Check the connection at startup
verify() connects and logs in without sending anything. Call it when your app boots so a wrong password shows up in your logs straight away:
try {
await transport.verify();
console.log('SMTP ready');
} catch (err) {
console.error('SMTP login failed', err);
}
Pooling for many emails
By default Nodemailer opens a new SMTP connection for each sendMail() call. If you send a batch, turn on pooling so connections are reused:
const transport = nodemailer.createTransport({
pool: true,
maxConnections: 3,
host: 'smtp.mailcandor.com',
port: 465,
secure: true,
auth: { user: 'mailcandor', pass: process.env.MAILCANDOR_KEY },
});
Keep maxConnections low. Providers limit how fast you can send, and opening many parallel connections just turns into rate-limit errors.
Attachments, CC and reply-to
await transport.sendMail({
from: 'Acme Billing <billing@acme.com>',
to: ['sam@example.com', 'finance@example.com'],
cc: 'accounts@acme.com',
replyTo: 'support@acme.com',
subject: 'Invoice 1042',
text: 'Your invoice is attached.',
attachments: [
{ filename: 'invoice-1042.pdf', path: './invoices/1042.pdf' },
{ filename: 'notes.txt', content: 'Paid in full' },
],
});
Note that Nodemailer uses replyTo in camelCase. Attachments can come from a file path, a Buffer or a string in content, or a URL in path.
Using Nodemailer with Gmail
You can point Nodemailer at Gmail’s SMTP server (smtp.gmail.com, port 465 or 587). Your normal Google password will not work: turn on 2-Step Verification and create an app password, or set up OAuth2. Gmail limits how much you can send and is built for personal mail, so it is fine for testing but not for password resets your users rely on. The Gmail SMTP settings guide has the details.
Using Nodemailer in Next.js
Nodemailer needs TCP sockets, so it works in Next.js route handlers and server actions on the default Node.js runtime, and fails on the Edge runtime. Create the transport in a server-only module so it is reused. The Next.js guide has a full example.
The alternative: an email API with fetch
If you are starting fresh, you may not need SMTP at all. Node 18 and later have fetch, and an email API takes one request per email:
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MAILCANDOR_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': 'invoice-1042',
},
body: JSON.stringify({
from: 'Acme Billing <billing@acme.com>',
to: 'sam@example.com',
subject: 'Invoice 1042',
text: 'Your invoice is attached.',
}),
});
if (!res.ok) throw new Error((await res.json()).error.message);
The response is a 202 with an email id. The Idempotency-Key header makes a retry safe: a repeat with the same key returns the first result instead of sending twice.
Common Nodemailer errors
EAUTH/ 535: wrong username or password. With Mailcandor the username ismailcandorand the password is the API key.ETIMEDOUTorECONNECTION: the port is blocked, which is common for port 25 and sometimes 587 on cloud hosts. Try 465 or the API.ESOCKETwith a TLS error:securedoes not match the port.
Nodemailer vs an email API
| Nodemailer (SMTP) | Email API (fetch) | |
|---|---|---|
| Dependencies | nodemailer | None on Node 18+ |
| Works on edge runtimes | No | Yes |
| Safe retries | Not built in | Idempotency keys |
| Delivery events | Usually none | Webhooks per email id |
| Best for | Existing SMTP code, libraries that only speak SMTP | New apps and serverless functions |
There is no wrong answer here. The SMTP vs API guide covers the trade-offs in more depth.
Before you send: verify your domain
Nodemailer will happily send from any address, but receiving servers check that the domain in from has SPF, DKIM and DMARC records. Without them your mail goes to spam or is rejected. Add your domain with your provider and publish the records it gives you; the SPF, DKIM and DMARC guide walks through each one.