Send with

Send email with Node.js

Node.js 18 and later include fetch, so you can call the API without installing anything.

Setup

Create an API key under Developers › API keys and put it in an environment variable:

export ROBUSTEMAIL_API_KEY="rb_test_..."

Send an email

// send.mjs
const API = "https://robustemail.com/api/v2";

export async function sendEmail(email, idempotencyKey) {
  const res = await fetch(`${API}/emails`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.ROBUSTEMAIL_API_KEY}`,
      "Content-Type": "application/json",
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: JSON.stringify(email),
  });

  const body = await res.json();
  if (!res.ok) {
    // { statusCode, name, message }
    throw new Error(`${body.name}: ${body.message}`);
  }
  return body.id;
}

const id = await sendEmail({
  from: "Acme <hello@acme.com>",
  to: "delivered@sandbox.robustemail.dev",
  subject: "Welcome to Acme",
  html: "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
}, "welcome-user-1042");

console.log("Queued", id);

Run it with node send.mjs. With a test key nothing is delivered; the email appears in Developers › Emails.

Attach a file

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

const pdf = await readFile("./invoice-2041.pdf");

await sendEmail({
  from: "Acme Billing <billing@acme.com>",
  to: "jane@example.com",
  subject: "Your invoice #2041",
  html: "<p>Your invoice is attached.</p>",
  attachments: [
    { filename: "invoice-2041.pdf", content: pdf.toString("base64"), content_type: "application/pdf" },
  ],
}, "invoice-2041");

Retry safely

Retry network errors, 429 and 5xx responses with the same idempotency key. A request that actually went through returns the same ID instead of sending twice:

async function sendWithRetry(email, key, attempts = 3) {
  for (let i = 1; ; i++) {
    try {
      return await sendEmail(email, key);
    } catch (err) {
      if (i >= attempts) throw err;
      await new Promise((r) => setTimeout(r, 500 * 2 ** i));
    }
  }
}

Next