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 with Node.js and Nodemailer: SMTP, HTML, attachments and errors

Send email from Node.js with Nodemailer: configure an SMTP transport for ports 587 and 465, send HTML and attachments, verify the connection, use pooling for volume and fix the common EAUTH and connection errors.

OH
Written by Omar Haddad
Regional Deliverability Analyst, Middle East and Africa
Reviewed by Amara Okafor
  • Published13 Jun 2024
  • Read time8 min
  • Length1,711 words
Share this guide

To send email from Node.js, install Nodemailer, create a transport with nodemailer.createTransport() pointing at your SMTP host, and call transporter.sendMail() with the from, to, subject and text or html. Use port 587 with secure: false (the connection upgrades through STARTTLS) or port 465 with secure: true (TLS from the first byte). Keep credentials in environment variables.

This guide covers a working setup, HTML and attachments, connection verification, pooling for volume, Gmail specifics, error handling and a troubleshooting table. The examples use ES modules and async/await and run on any currently supported Node.js version. If you are sending from a Next.js application, see Next.js email with route handlers for framework details.

Packagenodemailer from npm
Port 587secure: false, optionally requireTLS: true to refuse a downgrade
Port 465secure: true
Key callscreateTransport(), verify(), sendMail(), close() for pools
NeverPut the SMTP password in client-side code or commit it to git

Install and configure

npm install nodemailer
# optional: load .env files during local development
npm install dotenv
# .env  (never commit this file)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-username
SMTP_PASS=your-password
MAIL_FROM="Example App <[email protected]>"

A first working email

import "dotenv/config";
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,  // true for 465, false for 587
  requireTLS: Number(process.env.SMTP_PORT) !== 465,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
  connectionTimeout: 15000,
  greetingTimeout: 15000,
  socketTimeout: 30000,
});

const info = await transporter.sendMail({
  from: process.env.MAIL_FROM,
  to: "[email protected]",
  subject: "Your report is ready",
  text: "Hello, your report is ready to download.",
});

console.log("Accepted:", info.accepted, "Rejected:", info.rejected, "Id:", info.messageId);

Top-level await works in ES modules (a .mjs file or "type": "module" in package.json). In CommonJS, wrap the call in an async function. The secure flag is the part people misread: it does not mean "use encryption". secure: false means start unencrypted and upgrade with STARTTLS, which Nodemailer does automatically when the server offers it; requireTLS: true makes the send fail rather than fall back to plain text if the upgrade is not possible. Background on both modes is in SMTP settings, ports and authentication.

HTML body, attachments and embedded images

await transporter.sendMail({
  from: process.env.MAIL_FROM,
  to: ["[email protected]", "[email protected]"],
  cc: "[email protected]",
  replyTo: "[email protected]",
  subject: "Invoice 1001",
  text: "Your invoice is attached. View it online: https://example.com/invoices/1001",
  html: `<p>Hello,</p>
         <p>Your invoice is attached.</p>
         <p><img src="cid:[email protected]" alt="Example" width="120"></p>`,
  attachments: [
    { filename: "invoice-1001.pdf", path: "./invoices/1001.pdf" },
    { filename: "notes.txt", content: "Plain text content" },
    { filename: "logo.png", path: "./assets/logo.png", cid: "[email protected]" },
  ],
});

Always send both text and html; the message becomes multipart/alternative, which filters and assistive tools handle better than HTML alone. Attachments can come from a file path, a string, a Buffer or a stream. Setting cid embeds an image that the HTML references with cid:. Many clients block remote images by default, as described in why images are blocked, and embedded images add to message size. Keep attachments modest; the size arithmetic is in email size limits and MIME.

Verify the connection before sending

try {
  await transporter.verify();
  console.log("SMTP connection and credentials are valid");
} catch (err) {
  console.error("SMTP verification failed:", err.code, err.message);
  process.exit(1);
}

verify() connects, negotiates TLS and authenticates without sending a message. Run it at startup or in a health check so a wrong password shows up as a deployment failure and not as lost customer email.

Sending at volume: pooling and queues

const pooled = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: 587,
  secure: false,
  requireTLS: true,
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
  pool: true,
  maxConnections: 5,
  maxMessages: 100,
});

// when shutting down
pooled.close();

With pool: true, Nodemailer keeps connections open and reuses them, which avoids a TLS handshake and login for every message. Choose maxConnections to match what your provider allows; too many parallel connections trigger rate limiting. Do not send from inside a web request handler for anything non-trivial: put messages on a queue and let a worker send them, so a slow SMTP server does not hold requests open. Patterns for retries and idempotency are in reliable email sending design and rate limits, retries and backoff.

Using Gmail or another mailbox provider

Mailbox providers allow SMTP for low-volume use but impose sign-in rules and daily sending caps, and those rules change. For Gmail, current practice is an app password on an account with two-step verification, or OAuth2, with host smtp.gmail.com on port 465 or 587; basic username and password sign-in is no longer available for many accounts. Confirm the present requirements in Google's documentation. The details and limits are in Gmail SMTP settings. Mailbox providers are suited to personal projects and internal notifications; for customer mail from an application, use a transactional SMTP service or email API so you get authentication on your own domain, bounce handling and delivery events.

Error handling

try {
  const info = await transporter.sendMail(message);
  if (info.rejected.length) {
    console.warn("Rejected recipients:", info.rejected);
  }
} catch (err) {
  switch (err.code) {
    case "EAUTH":       console.error("Authentication failed", err.response); break;
    case "ECONNECTION": console.error("Could not connect", err.message); break;
    case "ETIMEDOUT":   console.error("Timed out", err.message); break;
    case "ESOCKET":     console.error("TLS or socket error", err.message); break;
    case "EENVELOPE":   console.error("Invalid envelope or recipients", err.message); break;
    default:            console.error("Send failed", err);
  }
  // err.responseCode: 4xx = temporary (retry later), 5xx = permanent
}

Nodemailer attaches err.code (its own category), err.response (the server text) and err.responseCode (the numeric SMTP reply) where available. Retry temporary 4xx replies with backoff, and treat 5xx as permanent. Meanings of the codes are in SMTP response codes.

Troubleshooting

SymptomLikely causeFix
EAUTH, 535Wrong username or password, or the provider needs an app password or API keyVerify credentials with verify(). See error 535
ECONNECTION or ETIMEDOUTPort blocked or wrong hostTest from the same host with openssl s_client; try 587 and 465. See connection timeouts
ESOCKET, wrong version numbersecure flag does not match the portsecure: true only with 465
Self-signed certificate in chainInterception proxy or wrong host nameFix the trust or host; do not set rejectUnauthorized: false in production
Message accepted but not receivedSpam placement or recipient server rejection laterCheck bounce events and domain authentication
Hangs and never resolvesNo timeouts setSet connectionTimeout, greetingTimeout and socketTimeout
Works locally, fails in the cloudProvider blocks outbound SMTP portsUse 587 or 465 or an HTTP email API

Test safely before real recipients

const testAccount = await nodemailer.createTestAccount();   // Ethereal, a fake SMTP service
const testTransport = nodemailer.createTransport({
  host: testAccount.smtp.host,
  port: testAccount.smtp.port,
  secure: testAccount.smtp.secure,
  auth: { user: testAccount.user, pass: testAccount.pass },
});
const sent = await testTransport.sendMail({ from: "[email protected]", to: "[email protected]", subject: "Preview", text: "Hi" });
console.log("Preview URL:", nodemailer.getTestMessageUrl(sent));

Nodemailer includes helpers for Ethereal, a service that accepts messages and shows them in a web preview without delivering them. It is handy for checking layout and headers in development and in continuous integration. For automated tests, Nodemailer also offers a JSON transport option that returns the composed message as data instead of sending it, which keeps unit tests fast and offline. Whichever you use, switch the transport through configuration, never through code edits, so production always uses the real one. A staging environment with its own sandbox is covered in testing email in staging.

Read the result of sendMail

The object returned by sendMail() tells you what the SMTP server said at submission time. accepted and rejected list recipient addresses the server took or refused, response carries the final server line (often including a queue identifier), and messageId is the Message-ID header Nodemailer generated. Accepted means the server took responsibility for delivery, not that the message reached the inbox. Later outcomes such as bounces, deferrals and complaints arrive asynchronously, by bounce message to the envelope sender or, with a delivery service, as webhook events. Store the message identifier next to your own record (an order or user id) so you can trace a complaint such as "I never got the email" back to a log entry.

Two practical habits help. First, set an explicit envelope option or a dedicated bounce domain if your provider supports it, so bounces return to a place you monitor. Second, handle the case where rejected is non-empty but the promise resolved, because partial acceptance is not an exception. Hard-bounced and complaining addresses should be suppressed so you stop sending to them; see suppression list management.

Running in serverless and container environments

Short-lived functions create a new transport on every cold start, so do not use pool: true there; open, send and let the connection close. Make sure the function waits for sendMail() to finish before returning, since some platforms freeze the process the moment the handler resolves, which silently drops unsent messages. Check that your platform allows outbound connections on the submission ports, because some serverless and hobby hosting tiers block them, and fall back to an HTTP-based email API if they do. Keep secrets in the platform's secret store, not in the repository or the image.

Security checklist

  • Never expose SMTP credentials to browsers. Frontend code should call your backend, which sends the email.
  • Do not build headers or recipients directly from unvalidated user input. Nodemailer rejects newlines in headers, but validate addresses and rate limit public forms.
  • Authenticate your From domain with SPF, DKIM and DMARC; see authenticating your sending domain.
  • Rotate credentials when people leave or keys leak, and use separate credentials per service.
  • Log message identifiers and results, never passwords.

Next steps

Get a plain-text message working against a test mailbox, then add HTML and attachments, then add verify(), timeouts and a queue. If you send through MigoSMTP, use smtp.migosmtp.com with port 587 (STARTTLS) or 465 (implicit TLS) as the host and port in the transport, with the credentials from your account. If you would rather send with an HTTP call than hold SMTP connections, compare the options in SMTP versus API.

Send from Node.js through a relay built for applications Authenticate your domain, send over SMTP and receive delivery events.

Explore the SMTP relay

References and further reading

Frequently asked questions

How do I send an email in Node.js?

Install Nodemailer, create a transport with your SMTP host, port and credentials, then call transporter.sendMail() with from, to, subject and text or html.

Should secure be true or false in Nodemailer?

Use secure: true for port 465, where TLS starts immediately, and secure: false for port 587, where the connection upgrades with STARTTLS. Add requireTLS: true on 587 to prevent a plain-text fallback.

Can I use Gmail with Nodemailer?

Yes for low volume, with an app password or OAuth2 on smtp.gmail.com. Google changes sign-in rules and sending caps, so confirm them in Google's current documentation.

How do I attach a file?

Add an attachments array to sendMail() with objects containing filename and path, content or a stream. Add cid to embed an image referenced in the HTML.

How do I send many emails efficiently?

Create the transport with pool: true, limit maxConnections to what your provider allows, and send from a queue worker rather than inside web requests.

Topics#node.js#nodemailer#smtp#javascript#attachments
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