Send transactional email from Node.js

Node.js 18 and newer include fetch, so you can call the JMSURF Mail API without installing anything. This guide gives you a small helper, then shows templates, batches and webhooks in Express.

Set up

  • A verified domain and an API key (quick start).
  • Put the key in your environment: JMSURF_MAIL_KEY=jm_live_… (a .env file that is not committed, or your host's settings).

A helper you can reuse

mail.js
const BASE = "https://api.jmsurfmail.co.ke/api/v1";

export async function sendEmail(email, { idempotencyKey } = {}) {
  const res = await fetch(`${BASE}/emails`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.JMSURF_MAIL_KEY}`,
      "Content-Type": "application/json",
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: JSON.stringify(email),
    signal: AbortSignal.timeout(20_000),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    const err = new Error(data.error || `HTTP ${res.status}`);
    err.code = data.code;
    err.status = res.status;
    throw err;
  }
  return data; // { id, status }
}
Use it
import { sendEmail } from "./mail.js";

const { id } = await sendEmail({
  from: "YourApp <[email protected]>",
  to: "[email protected]",
  subject: "Welcome to YourApp",
  html: "<p>Karibu! Your account is ready.</p>",
  text: "Karibu! Your account is ready.",
}, { idempotencyKey: "welcome-user-381" });

Templates

Node.js
await sendEmail({
  from: "YourApp <[email protected]>",
  to: user.email,
  template: "password-reset",
  variables: { name: user.firstName, link: resetUrl },
});

Batch: up to 100 emails per request

Node.js
const res = await fetch("https://api.jmsurfmail.co.ke/api/v1/emails/batch", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.JMSURF_MAIL_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    emails: customers.slice(0, 100).map((c) => ({
      from: "YourApp <[email protected]>",
      to: c.email,
      template: "monthly-statement",
      variables: { name: c.name, balance: c.balance },
    })),
  }),
});
const { data } = await res.json();
// data[i] is { id, status } or { error, code }, in the same order as you sent them

Check each item: one bad address does not stop the others.

Receive delivery events in Express

Express
import express from "express";
import crypto from "node:crypto";

const app = express();
app.post("/webhooks/jmsurf-mail", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("X-JMSURF-Signature") || "";
  const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = crypto.createHmac("sha256", process.env.JMSURF_WEBHOOK_SECRET)
    .update(`${t}.${req.body}`).digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
  if (!v1 || !fresh || v1.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected))) return res.sendStatus(401);

  const event = JSON.parse(req.body);
  if (event.type === "email.bounced") { /* flag event.data.recipient */ }
  res.sendStatus(200);
});

Keep the raw body for the signature check. More in the webhook signature guide.

Next.js and serverless

Call sendEmail from a route handler or server action, never from browser code: the API key must stay on the server. Use a send-only key for serverless functions that only send.

Nodemailer and SMTP

JMSURF Mail is an HTTPS API. There is no SMTP login for customers yet, so apps that can only send through SMTP need a few lines of code that call the API instead. Your own SMTP server can be added as a backup route in Settings.

Errors

Status and codeMeaning
400 invalid_jsonThe body is not JSON.
401 invalid_api_keyMissing, wrong or revoked key.
403 domain_not_verifiedThe From domain is not verified on your account.
403 insufficient_scopeA send-only key tried to read logs or manage domains.
413 too_largeThe email is over 10 MB.
422 validation_errorA field is missing or wrong; the message says which.
429 quota_exceededDaily or monthly allowance used.
429 rate_limitedMore than 20 requests a second on this key.
502 send_failedEvery delivery route refused it; the message says why.

Send your first email today

Free plan with 100 emails a month, no card needed. Questions? WhatsApp or call +254 712 504 593, or email [email protected].