Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 133 ยท Frameworks and Ecosystem

Sending Email with Nodemailer: SMTP, HTML Mail and Attachments

Learn how Nodemailer sends email from Node.js, how SMTP and MIME work underneath, how to send HTML, attachments and retries safely, and watch a mail travel over a local SMTP server.

Almost every application sends email sooner or later: a welcome message, a password reset link, an invoice, a weekly digest. The standard Node.js answer is Nodemailer, a library with no dependencies that builds the message, talks to a mail server, and hides the awkward parts of the format.

In this lesson you learn the pieces that matter in practice: the SMTP transport that connects to a mail server, the structure of an email (text, HTML, attachments), what you must never do (build messages from raw user input), and how to handle failures. You will also see what Nodemailer does for you, by watching a real message cross a real SMTP conversation. No network access is needed for that: you will start a tiny SMTP server on loopback inside the editor.

Nodemailer itself cannot be installed in the editor, so its code is read-only. The runnable parts use a few dozen lines of our own that speak the same protocol.

The shape of the Nodemailer API

Terminal
npm install nodemailer
JavaScript
import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  host: 'smtp.example.com',
  port: 587,                         // 587 = STARTTLS, 465 = TLS from the start
  secure: false,                     // false for 587, true for 465
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});

const info = await transporter.sendMail({
  from: '"Example Shop" <[email protected]>',
  to: '[email protected]',
  subject: 'Your order has shipped',
  text: 'Your order #1042 is on its way.',                   // plain-text version
  html: '<p>Your order <b>#1042</b> is on its way.</p>',    // HTML version
  attachments: [{ filename: 'invoice.pdf', path: './invoices/1042.pdf' }],
});

console.log(info.messageId, info.accepted, info.rejected);

A transporter is a reusable connection configuration. Create it once at start-up, not per message. sendMail returns a promise with accepted and rejected recipient lists, and the server's reply in info.response. Credentials come from environment variables (Secrets and Configuration), never from source code.

In development you do not want to send real mail. Use a catch-all sandbox such as a local MailHog or Mailpit container (SMTP on port 1025, a web inbox on 8025), or nodemailer.createTestAccount(), which gives you a throwaway inbox at ethereal.email with a preview URL for each message from nodemailer.getTestMessageUrl(info). In tests, nodemailer.createTransport({ jsonTransport: true }) builds the message and returns it as JSON without sending anything.

Besides SMTP, Nodemailer has other transports: sendmail: true pipes to the local sendmail program, and the SES and other API providers can be used as SMTP relays too. For production volume, most teams relay through a transactional provider (Amazon SES, Postmark, Mailgun, Resend and others) for deliverability, instead of running their own mail server.

What actually crosses the wire

SMTP is a plain-text, line-based conversation. The client says EHLO, names the envelope sender (MAIL FROM) and each recipient (RCPT TO), then sends the message after DATA, ending with a line containing only a dot. The server answers each step with a three-digit code, the same idea as HTTP status codes: 2xx success, 3xx "go on", 4xx a temporary failure (try again later), 5xx a permanent failure (do not retry).

sequenceDiagram
    participant C as Your app (Nodemailer)
    participant S as SMTP server
    S-->>C: 220 ready
    C->>S: EHLO app.local
    S-->>C: 250 hello
    C->>S: MAIL FROM sender
    S-->>C: 250 ok
    C->>S: RCPT TO recipient
    S-->>C: 250 ok
    C->>S: DATA
    S-->>C: 354 send the message
    C->>S: headers, body, attachments, then a lone dot
    S-->>C: 250 queued
    C->>S: QUIT
    S-->>C: 221 bye

One message is one short conversation. The envelope (MAIL FROM, RCPT TO) is separate from the headers in the message.

The message itself is formatted as MIME. Headers come first (From, To, Subject, Content-Type), then a blank line, then the body. When there is more than one part (text and HTML, or attachments), the message is multipart and the parts are separated by a random boundary string. Binary attachments are encoded as base64 text. Non-ASCII subjects use an encoded-word form such as =?UTF-8?B?...?=. Getting all of that right by hand is exactly what Nodemailer is for.

Watch a message travel

The example below starts a minimal SMTP server on loopback, then sends a message with a text part, an HTML part and an attachment using a tiny transport that follows the same steps. Our sendMail has the same options as Nodemailer's; the real one does much more (authentication, TLS, pooling, hundreds of edge cases).

Node.js A mini SMTP server and a mini sendMail on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study the received message. The Subject header was encoded because it contains รฉ. The two body versions sit inside multipart/alternative, so mail programs show the HTML when they can and the text otherwise; the attachment is a base64 block inside the outer multipart/mixed. Always send a plain-text part as well as HTML: it helps accessibility and spam scoring.

HTML mail and templates

Email clients render HTML like a browser from about 2005. Use tables for layout, inline styles, absolute image URLs (or cid: images attached to the message), and keep the design simple. Build the HTML with a template (see Template Engines: EJS) so data is escaped. A name like <img src=x onerror=...> in an email is as dangerous as in a web page, and in addition anything you put into a header (to, subject) from user input can allow header injection if a newline sneaks in. Nodemailer rejects most of it for you, but validate email addresses and never copy raw form fields into headers.

Failures, retries and queues

Sending email can be slow (hundreds of milliseconds to seconds) and it can fail for reasons that are not your fault: the provider is down, the mailbox is full, a spam filter delays you. Treat it as background work:

  • Do not send inside the request handler. Registering a user should not wait for an SMTP server. Put a job on a queue and return at once; see Message Queues and the Job Queue project.
  • Retry temporary failures, not permanent ones. SMTP tells you which is which: 4xx means retry with a growing delay, 5xx (mailbox does not exist, message rejected) means stop and record the failure.
  • Use a pool (pool: true in createTransport) when you send many messages, so connections are reused.
  • Set timeouts (connectionTimeout, socketTimeout) so a dead server cannot hang a worker.
  • Make the job idempotent. If a retry happens after the server accepted the message but before you recorded it, the user gets two emails. Store a message key and check it first.
Node.js Retry only the failures that can succeed later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The permanent failure is reported on the first attempt, which keeps your queue from hammering a server about a mailbox that will never exist. For anything that matters (password resets, receipts), log the final status of each message and watch the bounce rate: repeated hard bounces damage your sending reputation.

Deliverability in one paragraph

Mail that is sent successfully can still land in spam. For your own domain, publish SPF, DKIM and DMARC DNS records that prove your server may send for it (Nodemailer can sign with DKIM; a provider usually does it for you), send from a real address that can receive replies, include an unsubscribe link in bulk mail, and never send to purchased lists. You can inspect a domain's records with dns.resolveTxt as shown in UDP, DNS and Modern Protocols.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do SMTP reply codes starting with 4 and 5 mean?

    A 4xx reply says the problem may go away, so retry with a delay. A 5xx reply says the message or mailbox is rejected for good.
  2. 2. Why send both a text and an html part?

    multipart/alternative lets each client pick the best version. A plain-text fallback is also a quality signal.
  3. 3. Where should registration code call sendMail?

    Mail is slow and can fail. A queue keeps the request fast and lets you retry temporary failures.
  4. 4. In SMTP, what is the 'envelope'?

    Servers route mail using the envelope. The headers inside the message are what the recipient sees, and they can differ (as with BCC).

Summary

  • Nodemailer builds messages (text, HTML, attachments) and sends them through a reusable SMTP transporter; configuration comes from the environment.
  • SMTP is a text conversation with codes: 2xx success, 4xx retry later, 5xx permanent failure.
  • A message is MIME: headers, a blank line, parts separated by boundaries, binary content in base64, non-ASCII headers encoded.
  • Use a sandbox (Mailpit, Ethereal or jsonTransport) in development and tests; use a transactional provider in production.
  • Send mail from a queue, retry only temporary failures with backoff, set timeouts, and make jobs idempotent.
  • Escape template data, never put raw user input in headers, and set up SPF, DKIM and DMARC.

Next: The vm Module: Running Code in Contexts.