How to Send Email From Node.js
Send email from Node.js with Nodemailer: configure an SMTP transport, send text and HTML, add attachments, handle errors and test without a real inbox.

Node.js has no built-in SMTP client. The node:net and node:tls modules can open a socket to a mail server, but speaking SMTP by hand means handling greetings, STARTTLS upgrades, authentication mechanisms, dot-stuffing and multi-line replies. Almost everyone uses Nodemailer, a library with no runtime dependencies that has been the standard answer for years. This post shows how to configure a transport, send plain text and HTML messages, attach files, read the result, handle the errors you will meet, and test the whole thing without sending a real message. The samples use ES modules on Node.js 26, and Nodemailer is installed with npm install nodemailer.
What sending email actually involves
Your application does not deliver email to the recipient. It hands the message to an SMTP server, which accepts responsibility for it and relays it onward. That server might be your own mail host, a provider such as Amazon SES, Postmark or SendGrid, or a corporate relay. From Node.js the job is the same in every case: open a connection, authenticate, submit the message and read the server's reply.
Nodemailer models that with two objects. A transport holds the connection settings and is created once. A call to sendMail() on the transport submits one message. Creating the transport at startup and reusing it is the normal pattern, because it can pool connections and avoids a handshake per message.
Everything the server needs to know comes from five things: host, port, whether the connection is encrypted from the first byte, credentials, and the message. Keep the first four in environment variables, never in source.
Create a transport
import nodemailer from "nodemailer";
export const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT ?? 587),
secure: process.env.SMTP_SECURE === "true",
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});The secure option decides how TLS starts. With secure: true the connection is encrypted immediately, which is the usual setup for port 465. With secure: false the connection starts in plain text and Nodemailer upgrades it with STARTTLS if the server offers it, which is the usual setup for port 587. The Nodemailer documentation on SMTP transport explains this, and the mistake to avoid is setting secure: true on port 587, which fails with an SSL error because the server is speaking plain SMTP.
Credentials come from your provider. Many providers issue an app-specific password or an API-style key rather than the account password, and some require you to verify the sending domain before they accept messages from it.
Send a message
import { transporter } from "./mailer.js";
const info = await transporter.sendMail({
from: '"Example App" <[email protected]>',
to: "[email protected]",
subject: "Your report is ready",
text: "Hello Ada,\n\nYour report is ready to download.\n",
html: "<p>Hello Ada,</p><p>Your report is <strong>ready</strong> to download.</p>",
});
console.log(info.accepted);
console.log(info.rejected);
console.log(info.response);[ '[email protected]' ]
[]
250 2.0.0 OK queued as 7F3A91sendMail() returns a promise when you do not pass a callback, so await works directly. The resolved object lists the recipients the server accepted and rejected, the server's final response line, and a messageId. The response text is chosen by your provider, so yours will differ. What matters is the leading 250, which is the SMTP code for success.
Sending both text and html produces a multipart/alternative message. Mail clients that display HTML use that part, and the rest fall back to the plain text. Always include the text part. It improves accessibility, helps with spam filtering and keeps the message readable in clients that block HTML.
The from address must be one your server is allowed to send as. A provider will reject or silently rewrite a sender it has not verified, so a message that works in testing and fails in production is often a sender-domain problem rather than a code problem.
Several recipients, cc and reply-to
Address fields accept a comma-separated string or an array. Use replyTo when replies should go somewhere other than the sender, and bcc for hidden copies.
import { transporter } from "./mailer.js";
const info = await transporter.sendMail({
from: "[email protected]",
to: ["[email protected]", "[email protected]"],
cc: "[email protected]",
replyTo: "[email protected]",
subject: "Quarterly summary",
text: "The summary is attached to the shared folder.",
});
console.log(info.accepted.length);3The count includes every accepted address across to, cc and bcc, so three here. If a provider rejects one address and accepts the others, the call still resolves, and the bad address appears in rejected. Check that array if a partial failure matters to you, because a resolved promise does not mean every recipient was accepted.
Attachments
Attachments go in an array. Each entry names the file and gives the content from a path, a buffer, a string or a stream.
import { transporter } from "./mailer.js";
await transporter.sendMail({
from: "[email protected]",
to: "[email protected]",
subject: "Invoice 1042",
text: "Your invoice is attached.",
attachments: [
{ filename: "invoice-1042.pdf", path: "./out/invoice-1042.pdf" },
{
filename: "notes.txt",
content: "Payment due in 14 days.\n",
contentType: "text/plain",
},
],
});A path is read when the message is built. A stream is read as it is sent, so large files do not have to sit in memory, which is why you should prefer a stream or path for anything big. Keep total message size under what your provider allows, which is commonly in the tens of megabytes, and for large files send a download link instead.
Verify the connection at startup
verify() opens a connection, authenticates and closes it without sending anything. Calling it once when the process starts turns a bad password or a wrong port into an immediate failure, instead of a mystery on the first real message.
import { transporter } from "./mailer.js";
try {
await transporter.verify();
console.log("SMTP ready");
} catch (error) {
console.error("SMTP not ready:", error.code, error.message);
process.exitCode = 1;
}SMTP readyWith a wrong password the catch block prints something like SMTP not ready: EAUTH Invalid login: 535 Authentication failed, and the exact text depends on the server. Nodemailer sets error.code to a short string such as EAUTH for authentication, ECONNECTION or ETIMEDOUT for network problems and EENVELOPE for a bad address. Branch on code, not on the message.
Test without a real inbox
Pointing development at your production provider sends real email to real people. Two safer options exist.
The first is Ethereal, a fake SMTP service run by the Nodemailer authors. createTestAccount() creates a throwaway account, and getTestMessageUrl() returns a link where you can read what was "sent".
import nodemailer from "nodemailer";
const account = await nodemailer.createTestAccount();
const transporter = nodemailer.createTransport({
host: account.smtp.host,
port: account.smtp.port,
secure: account.smtp.secure,
auth: { user: account.user, pass: account.pass },
});
const info = await transporter.sendMail({
from: "[email protected]",
to: "[email protected]",
subject: "Hello from the test account",
text: "It works.",
});
console.log(nodemailer.getTestMessageUrl(info));https://ethereal.email/message/aB3dEfGhIjKlMnOpThe URL is different on every run. This needs network access to Ethereal but no signup.
The second option is a local catcher such as Mailpit or MailHog, a small SMTP server you run on your machine that stores messages and shows them in a web page. Point SMTP_HOST at localhost, set the port the tool uses, and omit auth. Your code does not change between environments, only the environment variables do, which is the property you want.
For unit tests you can avoid SMTP altogether. Nodemailer has a jsonTransport that builds the message and returns it as a JSON string instead of sending it.
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({ jsonTransport: true });
const info = await transporter.sendMail({
from: "[email protected]",
to: "[email protected]",
subject: "Test",
text: "Body",
});
const message = JSON.parse(info.message);
console.log(message.subject, message.to[0].address);Test [email protected]Inject the transport into the function that sends mail and use the JSON transport in tests. You then assert on the recipient and subject without a network.
Do not send from the request handler
An SMTP conversation can take seconds, and it can fail. If a user signs up and your handler awaits sendMail() before responding, a slow mail server makes your signup slow, and a mail outage makes your signup fail. Two changes fix it.
Respond first, send afterwards. At the least, catch and log errors from a promise you did not await, so they do not become unhandled rejections.
Better, put the message on a queue and send it from a worker that can retry with backoff. How to Run Background Jobs With BullMQ shows that pattern.
Retrying matters because SMTP failures come in two kinds. A 4xx reply is temporary, such as a greylisting delay or a full mailbox, and a retry later often succeeds. A 5xx reply is permanent, such as an address that does not exist, and retrying only adds to your reputation problem. Nodemailer exposes the numeric code as error.responseCode, so a worker can retry the 4xx cases and give up on the 5xx ones.
Deliverability is not a code problem
A message can be accepted by your provider and still land in spam. That is decided by DNS records and sending reputation, not by Node.js. Publish SPF and DKIM records for your sending domain, add a DMARC policy, and send from a real address on that domain. Your provider's setup guide lists the exact records. Nodemailer can also sign messages with DKIM itself through its dkim option, which is useful if you run your own server, but with a hosted provider the signing is usually done for you.


