Skip to content
jshacks.dev
Node.js

Build an Email Newsletter Sender With Node.js

Build a Node.js newsletter sender: CSV list, escaped templates, signed unsubscribe links, batched SMTP delivery and a dry-run mode you can trust.

8 min read
Summarize in AI
Flat illustration of an envelope and a notification bell, with the Node.js, Resend and Mailgun logos.

A newsletter sender looks like a loop over a list with one sendMail call inside it. That version works for ten subscribers and starts to hurt at a few hundred: one bad address stops the run, one template variable with an angle bracket breaks the layout, and nobody can unsubscribe without you editing a file. This post builds a sender that handles those cases with a handful of small modules. It targets Node.js 26 'Lithium', which is the LTS line since 2026-10-28, and it runs unchanged on the Node.js 24 and 22 maintenance lines. The only dependency is nodemailer, because speaking SMTP by hand is a poor use of an afternoon. Hashing and signing come from the built-in crypto module.

What the sender has to do

Before writing code it helps to list the jobs, because each one becomes a function with a narrow contract.

  • Read subscribers from a CSV file, skip anyone who is not active, and drop duplicate addresses.

  • Fill an HTML template with per-subscriber values, escaping every value so a name cannot inject markup.

  • Put a signed unsubscribe link in each message, so a link cannot be forged for someone else's address.

  • Send in small batches, record which addresses failed, and keep going instead of stopping at the first error.

  • Offer a dry-run mode that does everything except talk to the mail server.

Notice what is not on the list: scheduling, open tracking and a web form for sign-ups. Those are separate services. A sender that does these five things and nothing else is easy to test, and testing is where mail code usually falls short, because the real transport is slow and sends real mail.

Subscribers, templates and tokens

Keep the pure logic in one module with no network access. The functions take strings in and return strings out, so you can check them without a mail server.

newsletter.jsJavaScript
import { createHmac, timingSafeEqual } from "node:crypto";

export function parseSubscribers(csv) {
  const seen = new Set();
  const result = [];
  for (const line of csv.split("\n").slice(1)) {
    const [email, name, status] = line.split(",").map((s) => s.trim());
    if (!email || status !== "active") continue;
    const key = email.toLowerCase();
    if (seen.has(key)) continue;
    seen.add(key);
    result.push({ email: key, name: name || "there" });
  }
  return result;
}

const escapeHtml = (s) =>
  s
    .replace(/&/g, "&")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");

export function render(template, vars) {
  return template.replace(/\{\{(\w+)\}\}/g, (_, key) =>
    escapeHtml(String(vars[key] ?? "")),
  );
}

export function unsubscribeToken(email, secret) {
  return createHmac("sha256", secret).update(email).digest("hex").slice(0, 32);
}

export function verifyToken(email, token, secret) {
  const expected = Buffer.from(unsubscribeToken(email, secret));
  const given = Buffer.from(token);
  return expected.length === given.length && timingSafeEqual(expected, given);
}

Three details deserve a comment. The CSV parser lowercases addresses before it checks for duplicates, because [email protected] and [email protected] are the same mailbox for practical purposes, and sending twice is the quickest way to annoy a reader. It splits on a plain comma, so it does not handle quoted fields; if your list comes from a spreadsheet export with commas inside names, use a real CSV parser instead.

The template function escapes every value, including ones you wrote yourself. A subscriber who signed up as <script> should get a harmless greeting, and a title containing & should not produce invalid HTML. Escaping at the single point where values enter the template is easier to audit than remembering to escape at each call.

The unsubscribe token is an HMAC of the address under a server-side secret. The link https://example.com/[email protected]&t=<token> can be verified without a database lookup, and nobody can build a valid link for another address without the secret. The comparison uses timingSafeEqual from the crypto API, which throws on buffers of different lengths, so the length check comes first. Truncating the hex digest to 32 characters keeps URLs short and still leaves 128 bits to guess.

A short script exercises all four functions.

check-newsletter.jsJavaScript
import {
  parseSubscribers,
  render,
  unsubscribeToken,
  verifyToken,
} from "./newsletter.js";

const csv = [
  "email,name,status",
  "[email protected],Ana,active",
  "[email protected],,active",
  "[email protected],Ana,active",
  "[email protected],Cy,unsubscribed",
].join("\n");

for (const s of parseSubscribers(csv)) {
  console.log(`${s.email} ${s.name}`);
}

console.log(render("Hi {{name}}, read {{title}}", { name: "<Ana>", title: "Q&A" }));

const secret = "test-secret";
const token = unsubscribeToken("[email protected]", secret);
console.log(token.length);
console.log(verifyToken("[email protected]", token, secret));
console.log(verifyToken("[email protected]", token, secret));
console.log(verifyToken("[email protected]", "short", secret));

The list has four lines of data. The second line is a duplicate of the first with different casing, and the last is unsubscribed, so two subscribers remain. The token is 32 characters, it verifies for its own address, and it fails for another address and for a token of the wrong length.

Text
[email protected] Ana
[email protected] there
Hi &lt;Ana&gt;, read Q&amp;A
32
true
false
false

Sending in batches without stopping on errors

Mail servers rate-limit, and some reject a connection that opens too many messages at once. Sending in small groups with a pause between them is polite and predictable. The sender function below takes the actual send as a parameter. That one choice makes the dry-run mode and the tests trivial, because you pass a fake instead of a transport.

send-all.jsJavaScript
import { setTimeout as sleep } from "node:timers/promises";

export async function sendAll(subscribers, send, { batchSize = 2, pauseMs = 0 } = {}) {
  const failed = [];
  for (let i = 0; i < subscribers.length; i += batchSize) {
    const batch = subscribers.slice(i, i + batchSize);
    const results = await Promise.allSettled(batch.map((s) => send(s)));
    let ok = 0;
    results.forEach((r, index) => {
      if (r.status === "fulfilled") ok += 1;
      else failed.push(batch[index].email);
    });
    console.log(`batch ${i / batchSize + 1}: ${ok} sent, ${batch.length - ok} failed`);
    if (pauseMs > 0 && i + batchSize < subscribers.length) await sleep(pauseMs);
  }
  return failed;
}

const people = [
  { email: "[email protected]" },
  { email: "[email protected]" },
  { email: "[email protected]" },
];

const failed = await sendAll(people, async (s) => {
  if (s.email === "[email protected]") throw new Error("mailbox full");
});
console.log(`failed: ${failed.join(", ")}`);

Promise.allSettled is the important call. Promise.all would reject on the first failure and the rest of the batch would be left in an unknown state. With allSettled every message gets an outcome, and the function returns the failed addresses so the caller can retry them or write them to a file. The first batch holds Ana and Bo, and Bo's send throws; the second batch holds Cy alone.

Text
batch 1: 1 sent, 1 failed
batch 2: 1 sent, 0 failed
failed: [email protected]

Two rules keep this honest in production. Retry only temporary failures, which SMTP marks with 4xx response codes, and never retry a 5xx rejection, because that address is not going to start working. And keep the pause generous; your provider's documented sending limit is the number to follow, not whatever happens to work today.

The command that ties it together

The last module reads the list, builds each message and chooses a transport. In dry-run mode the transport is an object with the same sendMail method that prints instead of sending, so the rest of the code path runs for real, including template rendering and token creation.

send.jsJavaScript
import { readFileSync } from "node:fs";
import nodemailer from "nodemailer";
import { parseSubscribers, render, unsubscribeToken } from "./newsletter.js";
import { sendAll } from "./send-all.js";

const dryRun = process.argv.includes("--dry-run");
const secret = process.env.UNSUBSCRIBE_SECRET ?? "dev-secret";
const template = readFileSync("issue.html", "utf8");
const subscribers = parseSubscribers(readFileSync("subscribers.csv", "utf8"));

const transport = dryRun
  ? { sendMail: async (m) => console.log(`would send to ${m.to}`) }
  : nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: 587,
      auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
    });

const failed = await sendAll(
  subscribers,
  (s) =>
    transport.sendMail({
      from: "News <[email protected]>",
      to: s.email,
      subject: "Issue 12",
      html: render(template, {
        name: s.name,
        token: unsubscribeToken(s.email, secret),
      }),
    }),
  { batchSize: 20, pauseMs: 1000 },
);

process.exitCode = failed.length > 0 ? 1 : 0;

With the two subscribers from the earlier list, node send.js --dry-run prints one line per message and one batch summary. Because the batch size is 20, both addresses fall in batch 1.

Text
would send to [email protected]
would send to [email protected]
batch 1: 2 sent, 0 failed

The exit code is the last useful detail. A scheduler or CI job sees a non-zero code when any address failed, so a partial run does not look like a success. In a live run you would write the failed addresses to a file rather than only counting them.

Details that decide whether mail arrives

Code is the smaller half of newsletter delivery. Authentication matters more: publish SPF and DKIM records for the sending domain, and a DMARC policy, or large mailbox providers will filter your mail whatever the HTML looks like. Add a List-Unsubscribe header with the same signed link and, for bulk mail, List-Unsubscribe-Post: List-Unsubscribe=One-Click, which the major providers now expect. In nodemailer the headers option on the message carries these.

Send a plain-text alternative with the text option next to html. Some readers prefer it and spam filters notice when it is missing. Keep the template small and the images hosted, since attached images inflate every message by the size of the image times the list length.

Store unsubscribes the moment the link is clicked, and re-read the list at the start of every send. A subscriber who unsubscribed ten minutes ago must not get the next issue because a cached copy of the CSV said otherwise.

Where this design stops

This sender suits a list of a few thousand people and a person who runs it by hand or from a scheduler. It is single-process, it has no queue, and a crash in the middle of a run loses track of who already received the issue. The fix is to record each successful address as you go and skip those on restart, which is a small extension of the failed array. Past tens of thousands of recipients, or when you need bounce processing and complaint handling, a transactional email provider's API does that work better than a custom SMTP loop. The pure functions in newsletter.js still carry over unchanged.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.