Send with

Send email with Express

Express runs on Node.js, which has fetch built in from version 18, so no extra package is needed to call the API.

Setup

npm install express
export ROBUSTEMAIL_API_KEY="rb_test_..."

A reusable helper

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

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

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

export const escapeHtml = (s) =>
  String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);

Send from a route

// server.mjs
import express from "express";
import { sendEmail, escapeHtml } from "./email.mjs";

const app = express();
app.use(express.json());

app.post("/signup", async (req, res) => {
  const { email, name } = req.body;
  const user = await createUser({ email, name }); // your own code

  try {
    const emailId = await sendEmail({
      from: "Acme <hello@acme.com>",
      to: user.email,
      subject: "Welcome to Acme",
      html: `<p>Hi ${escapeHtml(user.name)}, thanks for signing up.</p>`,
    }, `welcome-user-${user.id}`);

    res.status(201).json({ ok: true, emailId });
  } catch (err) {
    console.error("Welcome email failed", err);
    // The account exists, so do not fail the sign-up because of the email
    res.status(201).json({ ok: true, emailId: null });
  }
});

app.listen(3000);

The idempotency key is built from the user’s ID. If the request is retried, the API returns the first email instead of sending a second one.

Tips

  • Escape user input that goes into HTML, as escapeHtml does above.
  • Move slow work to a queue. For bulk or non-urgent email, push a job to a queue such as BullMQ and send from a worker, reusing the same idempotency key on retries.
  • Test without sending. Keys starting with rb_test_ and addresses at sandbox.robustemail.dev never deliver. See Test mode.

Next