How to send email with Node.js

Send email from Node.js with the REST API and Node's built-in fetch, or over SMTP with Nodemailer: attachments, safe retries, errors and delivery checks.

What you need

Send with the REST API

One POST to /v1/emails sends a message. Save this as send.mjs and run it with node send.mjs:

const response = await fetch('https://api.snd.email/v1/emails', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.SND_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': 'order-8812-receipt',
  },
  body: JSON.stringify({
    from: 'Acme <receipts@acme.example>',
    to: 'jo@acme.example',
    subject: 'Your receipt',
    text: 'Thanks for your order.',
  }),
});

const result = await response.json();
if (!response.ok) {
  throw new Error(`${response.status} ${result.code}: ${result.detail}`);
}
console.log(response.status, result.id, result.messages);

The from address must be at a verified domain that the key may send from, as an address or as Name <address>. to is one address or a list; to, cc and bcc together hold at most 50 addresses. Give text, html or both.

The answer is 202 Accepted with the id of the request and one message per recipient, each with its own id. A message's status is queued, or suppressed when the address is on your suppression list and nothing is sent to it.

The same request can carry cc, bcc, reply_to, up to 5 tags, up to 10 metadata keys and custom headers. Every field is in the reference.

Send over SMTP

If your app already sends mail with Nodemailer, point it at the SMTP relay instead. SMTP is off until an Owner turns it on: in the dashboard, open SMTP and press Activate. Then install Nodemailer with npm install nodemailer:

import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
  host: 'smtp.snd.email',
  port: 587,
  secure: false,
  requireTLS: true,
  auth: { user: 'snd', pass: process.env.SND_API_KEY },
});

const info = await transporter.sendMail({
  from: 'Acme <receipts@acme.example>',
  to: 'jo@acme.example',
  subject: 'Your receipt',
  text: 'Thanks for your order.',
});
console.log(info.response);

The username can be any value; the password is the API key. Port 587 switches to TLS with STARTTLS before it logs in, and requireTLS makes sure it does. Port 2525 works the same way where a host blocks 587. On port 465, which is TLS from the first byte, set secure: true and leave out requireTLS. Port 25 is not offered.

Add an attachment

Over the REST API a file goes in the attachments list with its name, its bytes as base64 and its media type:

import { readFile } from 'node:fs/promises';

const pdf = await readFile('invoice.pdf');
const attachments = [
  { filename: 'invoice.pdf', content: pdf.toString('base64'), content_type: 'application/pdf' },
];
// Add `attachments` to the body of the request above, beside `text`.

The whole message is at most 10,000,000 bytes, headers and attachments included, with at most 100 files. Base64 makes a file about a third larger, so the largest file a message can carry is about 7.3 MB. A larger message is refused with 413 (payload_too_large), and a blocked file type, such as a program or an Office file with macros, with 422 (attachment_forbidden). With Nodemailer, pass attachments: [{ path: 'invoice.pdf' }] to sendMail.

Make retries safe

A network error can leave you not knowing whether a message was accepted. The Idempotency-Key header makes a retry safe: send the same key with the same body again, and you get the first answer back, with the header Idempotent-Replayed: true, while nothing is sent twice. Take the key from your own data, such as the order the receipt is for.

Handle errors

Every error has a status of 400 or above and a body of type application/problem+json with type, title, status, code and detail. Act on code; each code has its own page:

StatusCodeWhat to do
400invalid_requestFix the field that errors[0].pointer names.
401unauthorizedCheck the key: it is missing, unknown, revoked or malformed.
403domain_out_of_scopeThe key may not send from the from domain: use a key for that domain.
422domain_not_verified, domain_declaration_requiredFinish the domain's setup in the dashboard.
429rate_limitedToo many requests at once: wait the seconds Retry-After names, at most a minute, then retry with the same Idempotency-Key.
429send_limit_reachedYour daily or monthly sending limit is used up. Do not retry: the daily limit starts again at 00:00 UTC, the monthly one on the first day of the month (UTC) on Free and with the plan's next monthly window on a paid plan; to raise it, contact support. With limit big_mail, large mail awaiting delivery fills its budget: retry after Retry-After.

A send that retries only what a retry can fix: rate_limited (by the problem's type), a server error and a network error. It waits as Retry-After asks but never more than 60 seconds, tries 3 times at most, and keeps the same Idempotency-Key. A daily or monthly send_limit_reached is final: its Retry-After can be weeks away; a big_mail one is retried.

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

async function send(body, idempotencyKey) {
  for (let attempt = 1; ; attempt += 1) {
    let response;
    try {
      response = await fetch('https://api.snd.email/v1/emails', {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.SND_API_KEY}`,
          'Content-Type': 'application/json',
          'Idempotency-Key': idempotencyKey,
        },
        body: JSON.stringify(body),
      });
    } catch (error) {
      if (attempt === 3) throw error; // a network error, three times
      await sleep(1);
      continue;
    }
    const result = await response.json().catch(() => ({}));
    if (response.ok) return result;
    const retry = response.status >= 500 || String(result.type).endsWith('/errors/rate_limited') || result.limit === 'big_mail';
    if (!retry || attempt === 3) {
      // Final: a daily or monthly send_limit_reached starts again at 00:00 UTC or with the next monthly window.
      throw new Error(`${response.status} ${result.code}: ${result.detail}`);
    }
    await sleep(Math.min(Number(response.headers.get('Retry-After')) || 1, 60));
  }
}

const result = await send(
  { from: 'Acme <receipts@acme.example>', to: 'jo@acme.example', subject: 'Your receipt', text: 'Thanks for your order.' },
  'order-8812-receipt',
);
console.log(result.id);

All codes are in the error list.

Check delivery

GET /v1/emails/{id} with a message id returns its status and its newest 200 events. It needs a key with the emails:read scope:

const id = '1b9e4f7a-3c2d-4e5f-8a6b-7c9d0e1f2a3b';
const response = await fetch(`https://api.snd.email/v1/emails/${id}`, {
  headers: { Authorization: `Bearer ${process.env.SND_READ_KEY}` },
});
const message = await response.json();
console.log(message.status, message.events.map((e) => e.type));

Rather than asking, let us tell you: a webhook sends each delivery, bounce, open or click to your endpoint as a signed request.

Troubleshooting

More on the API: the email API and the quick start.