Skip to content

Node.js quickstart

Send a message from Node.js with the built-in fetch function.

  1. A Comail account with an enrolled, DNS-verified sending domain. Sign up if you need an account.
  2. Your account ID (DID) and an API key for your sending domain. Open API keys in the Builders console to create a key. Copy the key when it appears and keep it out of client-side code and source control. To replace a lost key, follow the API key guide.
  3. Node 18 or newer (node --version), which includes fetch.
  4. A real recipient address you can check. Replace example.com in the examples below; the relay rejects IANA example domains with 422 INVALID_RECIPIENT_DOMAIN.

Save as send.mjs:

const { COMAIL_DID, COMAIL_API_KEY } = process.env;
if (!COMAIL_DID || !COMAIL_API_KEY) {
console.error("Set COMAIL_DID and COMAIL_API_KEY");
process.exit(1);
}
const res = await fetch("https://smtp.atmos.email/v1/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Atmos-DID": COMAIL_DID,
"Authorization": `Bearer ${COMAIL_API_KEY}`,
},
body: JSON.stringify({
from: "you@yourdomain.com",
to: "alice@example.com",
subject: "Hello from comail",
text: "If you can read this, the API key works.",
}),
});
const result = await res.json().catch(() => null);
if (!res.ok || !result) {
const detail = result?.error ?? "no error details";
console.error(`send failed: HTTP ${res.status} ${result?.code ?? ""} ${detail}`);
for (const r of result?.rejected ?? []) {
console.error(` ${r.recipient}: ${r.error}`);
}
process.exit(1);
}
console.log(`accepted: ${result.accepted.length}`);
console.log(`rejected: ${result.rejected?.length ?? 0}`);
for (const r of result.accepted) {
console.log(` → ${r.recipient} (messageId: ${r.messageId})`);
}

In send.mjs, replace you@yourdomain.com with your sending address and alice@example.com with your own recipient address. Set your DID and API key in the shell, then run the example.

Terminal window
export COMAIL_DID=did:plc:your-did-here
export COMAIL_API_KEY=atmos_your-api-key
node send.mjs

Expected output when the relay accepts the message:

accepted: 1
rejected: 0
→ alice@example.com (messageId: 12345)

Look for your recipient and its messageId in accepted. That entry means Relay queued the message. Check your account or the Events API for the delivery result. If the domain is in its first 14 days of sending, check the recipient’s spam folder too.

For a module you can import across a project:

comail.mjs
const COMAIL_DID = process.env.COMAIL_DID;
const COMAIL_API_KEY = process.env.COMAIL_API_KEY;
if (!COMAIL_DID || !COMAIL_API_KEY) {
throw new Error("Set COMAIL_DID and COMAIL_API_KEY in the environment.");
}
export async function sendMail({ from, to, subject, text, html, replyTo, category, headers }) {
const res = await fetch("https://smtp.atmos.email/v1/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Atmos-DID": COMAIL_DID,
"Authorization": `Bearer ${COMAIL_API_KEY}`,
},
body: JSON.stringify({ from, to, subject, text, html, replyTo, category, headers }),
});
const body = await res.json().catch(() => null);
if (!res.ok || !body) {
const rejected = body?.rejected ?? [];
const detail = body?.error ?? (rejected.length ? "all recipients rejected" : "no error details");
const err = new Error(`comail send failed: HTTP ${res.status}: ${detail}`);
err.status = res.status;
err.code = body?.code;
err.rejected = rejected;
throw err;
}
return body;
}

Replace the from and to addresses with your enrolled domain and real recipients, and run with COMAIL_DID and COMAIL_API_KEY set in the environment:

import { sendMail } from "./comail.mjs";
const result = await sendMail({
from: "auth@yourdomain.com",
to: ["alice@example.com", "bob@example.com"],
subject: "Sign-in link",
text: "https://your-app.com/auth?token=abc123",
category: "login-link",
});
console.log(`accepted: ${result.accepted.length}, rejected: ${result.rejected?.length ?? 0}`);

fetch resolves even for HTTP 4xx and 5xx responses. The helper checks res.ok and copies the relay’s error into the error message and its code into a separate field when available. A gateway may return a response that isn’t JSON, so the helper also reports the HTTP status.

try {
await sendMail({ /* ... */ });
} catch (err) {
switch (err.code) {
case "RATE_LIMITED":
// Domain or account limit. Retry after the window resets.
break;
case "DOMAIN_MISMATCH":
// from: address domain isn't enrolled under this DID.
break;
case "SUSPENDED":
case "PENDING":
// Account-level issue. Check /account.
break;
case "INVALID_REQUEST":
// Bad input: missing field, CRLF in headers, body > 1 MiB,
// > 50 recipients, etc.
break;
case "QUEUE_FULL":
case "TEMPORARILY_UNAVAILABLE":
// Server-side. Safe to retry with backoff.
break;
default:
throw err;
}
}

See HTTP Send API for the full code table.

to accepts either a string or an array of up to 50 addresses. In a multi-recipient call, an HTTP 200 response lists the queued addresses in accepted and includes rejected only when an address failed. If the relay returns only failures, the helper makes the list available as err.rejected. Check each failure and retry only the addresses that failed temporarily.

const result = await sendMail({
from: "news@yourdomain.com",
to: ["alice@example.com", "bob@example.com", "carol@example.com"],
subject: "Acme weekly",
html: "<p>This week's updates...</p>",
category: "bulk",
});
for (const r of result.accepted) {
console.log(`OK ${r.recipient}: ${r.messageId}`);
}
for (const r of result.rejected ?? []) {
console.log(`ERR ${r.recipient}: ${r.error}`);
}

The relay assigns one messageId to each queued recipient. The response contains it as a 64-bit JSON integer. JavaScript’s usual JSON parser can round an integer above Number.MAX_SAFE_INTEGER. If you need the exact value across the full 64-bit range, read the response text with a parser that preserves large integers. Converting a number after rounding cannot recover the original ID.

Back to docs