How to send an email using nodemailer

By

Published · Updated

Tagged: Node.js

Learn how to send an email from Node.js using Nodemailer 10: create an SMTP transporter, send to multiple recipients, add attachments, check the connection with verify(), fix common errors and test with Ethereal.

To send an email from Node.js with nodemailer, you create a transporter pointing at an SMTP server, define the message, and call sendMail().

Nodemailer is the standard library for this job. Node has no built-in way to send email, and talking SMTP by hand is not something you want to do. Nodemailer handles the protocol, the authentication, and the message encoding for you.

Nodemailer 10 needs Node 20 or newer. If you’re still on an older Node line, upgrade first (current LTS is Node 24).

You need SMTP credentials from an email provider. Services like Amazon SES, Postmark or Resend give you a host, a username and a password when you sign up.

First install it:

npm install nodemailer

Then import it in your Node script or app:

import nodemailer from 'nodemailer'

Create the transporter

Initialize a transporter object that we’ll use later to send the email. It holds the connection settings for your SMTP server:

const transporter = nodemailer.createTransport({
  host: 'smtp.yoursmtpserver.com',
  port: 465,
  secure: true,
  auth: {
    user: 'smtp_user',
    pass: 'smtp_pass',
  },
})

⚠️ NOTE: you need to fill those values with real SMTP server credentials

A note on ports: secure: true is for port 465, which uses TLS from the start. If your provider gives you port 587, set secure: false. Nodemailer will then upgrade the connection with STARTTLS. Mixing these up is the most common reason the connection fails or hangs.

Define and send the message

Now create an options object with the details of the email you want to send:

const options = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Hi!',
  html: '<p>Hello</p>',
}

You can use text instead of html for a plain text body, or include both.

Finally call the sendMail() method on the transporter object, passing options and a callback that will be executed when it’s finished:

transporter.sendMail(options, (err, info) => {
  if (err) {
    console.log(err)
  } else {
    console.log('EMAIL SENT', info.messageId)
  }
})

This also accepts a promise-based syntax:

const info = await transporter.sendMail(options)
console.log(info.messageId)

If you prefer writing the rest of the script with async/await, this form fits better.

The info object tells you what happened:

A successful sendMail() means the SMTP server accepted the message. It doesn’t mean it reached the inbox. The server can still bounce it later or the recipient’s provider can put it in spam.

Check the connection with verify()

Before sending anything, you can check that the settings are right:

try {
  await transporter.verify()
  console.log('SMTP server is ready')
} catch (err) {
  console.error(err)
}

verify() connects to the server and logs in, without sending a message. It catches a wrong host, a wrong port and wrong credentials. It doesn’t check that the server will accept your from address.

A good place to call it is when the app starts, so a broken config shows up right away and not when the first user tries to reset their password.

Common errors

Errors from Nodemailer have a code property. These are the ones you’ll see most:

err.codeWhat it usually means
EAUTHWrong username or password. The message includes the server reply, like 535 Invalid login
ETIMEDOUT with Greeting never receivedYou set secure: false on port 465. Nodemailer waits for a plain greeting while the server waits for TLS
ESOCKET with wrong version numberYou set secure: true on a port that expects a plain connection first, like 587
ESOCKET with ECONNREFUSEDNothing is listening on that host and port, or a firewall blocks it
EENVELOPEA problem with the sender or the recipients, like no recipients at all

The Greeting never received error is the annoying one, because by default Nodemailer waits 30 seconds before giving up, so it looks like the script hangs.

If you leave secure out and use port 465, Nodemailer sets secure: true for you.

Multiple recipients, cc, bcc and reply-to

to, cc and bcc accept one address, a comma-separated string, or an array. You can add a display name in the "Name" <address> format:

const options = {
  from: '"Flavio" <[email protected]>',
  to: ['[email protected]', '"Bob" <[email protected]>'],
  cc: '[email protected], [email protected]',
  bcc: '[email protected]',
  replyTo: '[email protected]',
  subject: 'Hi!',
  text: 'Hello',
  html: '<p>Hello</p>',
}

Recipients in bcc get the email, but Nodemailer doesn’t write a Bcc header, so nobody sees them. I checked the raw message to be sure.

replyTo sets the address that the “Reply” button uses, when it’s different from from.

If you send to many people at once, everyone in to and cc sees all the other addresses. For newsletters or notifications, send one email per recipient instead.

Attachments

Add an attachments array. Each attachment can point to a file with path, or contain the data directly with content:

const options = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Your report',
  text: 'The report is attached.',
  attachments: [
    {
      filename: 'report.pdf',
      path: './report.pdf',
    },
    {
      filename: 'notes.txt',
      content: 'Some notes',
    },
  ],
}

content can be a string, a Buffer or a readable stream. path can also be an HTTPS URL, and Nodemailer downloads the file when it sends the email. Nodemailer guesses the content type from the file name, and you can set contentType if you need to.

To show an image inside the HTML body instead of as an attachment, give it a cid and use that in the src:

const options = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Logo',
  html: '<p>Here is the logo: <img src="cid:logo@flaviocopes"></p>',
  attachments: [
    {
      filename: 'logo.png',
      path: './logo.png',
      cid: 'logo@flaviocopes',
    },
  ],
}

Test without sending real emails

While you build, you don’t want to send emails to real people. Nodemailer works with Ethereal, a fake SMTP service: it accepts the email and shows it in a web page, but never delivers it.

createTestAccount() creates a throwaway Ethereal account for you:

import nodemailer from 'nodemailer'

const testAccount = await nodemailer.createTestAccount()

const transporter = nodemailer.createTransport({
  host: 'smtp.ethereal.email',
  port: 587,
  secure: false,
  auth: {
    user: testAccount.user,
    pass: testAccount.pass,
  },
})

const info = await transporter.sendMail({
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Test',
  text: 'Hello',
})

console.log(nodemailer.getTestMessageUrl(info))

Open the URL it prints to see the email as it would arrive, headers included.

Keep credentials out of the code

Don’t hardcode the SMTP password in your source. Put it in an environment variable:

auth: {
  user: process.env.SMTP_USER,
  pass: process.env.SMTP_PASS,
},

It’s easy to forget a hardcoded password and push it to a public repo.

One last tip: if your emails end up in spam, the problem is usually your domain’s DNS setup. See how to send email properly for sending subdomains, authentication and message headers. I made a tool to generate and explain SPF, DKIM and DMARC records.

Want me to talk about your product? You can sponsor this site.

Related posts about node: