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.envfile that is not committed, or your host's settings).
A helper you can reuse
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 }
}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
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
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 themCheck each item: one bad address does not stop the others.
Receive delivery events in 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 code | Meaning |
|---|---|
| 400 invalid_json | The body is not JSON. |
| 401 invalid_api_key | Missing, wrong or revoked key. |
| 403 domain_not_verified | The From domain is not verified on your account. |
| 403 insufficient_scope | A send-only key tried to read logs or manage domains. |
| 413 too_large | The email is over 10 MB. |
| 422 validation_error | A field is missing or wrong; the message says which. |
| 429 quota_exceeded | Daily or monthly allowance used. |
| 429 rate_limited | More than 20 requests a second on this key. |
| 502 send_failed | Every 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].