Node.js

Node.js email with Hermaily

Two ways from Node.js: Nodemailer over SMTP, if your code already uses it, or a plain fetch to the HTTP API, with no dependency, which gives you the message id, tags and metadata right away. Both share limits, suppressions and webhooks.

  • API POST /v1/send
  • SMTP smtp.hermaily.com:587
  • Node.js 18+ (fetch)

Before you start

Three things from Hermaily before the first message:

  1. An account. Create one (there is a free plan). New accounts are reviewed before they can send; you can set everything up in the meantime.
  2. A verified domain. In Domains, the assistant gives you the DKIM, SPF and DMARC records and checks they are published. You can only send from addresses on that domain or its subdomains.
  3. An API key for that domain, created in API keys. It starts with hm_ and is shown only once: keep it in your secrets manager or in the environment, never in the repository. The same key is the SMTP password; the username is apikey.

Configuration

Environment variables used in the examples:

.env
HERMAILY_API_KEY=hm_your_api_key
HERMAILY_WEBHOOK_SECRET=hmwh_your_webhook_secret
MAIL_FROM="Acme <hello@acme.example>"

MAIL_FROM must be on your verified domain. Never send the key to the browser: these calls belong on the server.

Send a message

With Nodemailer (SMTP)

Node.js · Nodemailer
import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "smtp.hermaily.com",
  port: 587,
  secure: false,        // STARTTLS on 587; for 465 use secure: true
  requireTLS: true,
  auth: { user: "apikey", pass: process.env.HERMAILY_API_KEY },
});

const info = await transporter.sendMail({
  from: process.env.MAIL_FROM,
  to: "lucia@example.com",
  subject: "Your order is on its way",
  text: "Hi Lucía, order 48213 has shipped.",
  html: "<p>Hi Lucía, order <b>48213</b> has shipped.</p>",
  headers: { "X-Entity-Ref-ID": "48213" },
});
console.log(info.response); // "250 2.0.0 Ok: queued as <id>"

For a newsletter add "X-Hermaily-Stream": "broadcast" to headers (paid plans, one recipient per message). Messages sent over SMTP are not rewritten, so there is no click tracking.

With fetch (HTTP API)

Node.js · fetch
// Node.js 18 or later: fetch is built in.
export async function sendEmail(message) {
  const res = await fetch("https://api.hermaily.com/v1/send", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.HERMAILY_API_KEY}`,
      "Content-Type": "application/json",
      "Accept-Language": "en",
    },
    body: JSON.stringify({ from: process.env.MAIL_FROM, ...message }),
  });
  if (res.status !== 202) {
    // { "error": { "code", "message" } }, or plain text if the JSON itself is wrong
    throw new Error(`Hermaily ${res.status}: ${await res.text()}`);
  }
  return res.json(); // { id, to, submitted_at, status: "queued" | "held" | "suppressed" }
}

const { id } = await sendEmail({
  to: "lucia@example.com",
  subject: "Your order is on its way",
  html: "<p>Hi Lucía, order <b>48213</b> has shipped.</p>",
  text: "Hi Lucía, order 48213 has shipped.",
  tags: ["shipping"],
  metadata: { order_id: "48213" },
});

The fields are those of POST /v1/send: from, to, cc, bcc, reply_to, subject, html, text, headers, attachments, tags, metadata, stream, track_opens and track_clicks. Up to 500 messages per request with POST /v1/send/batch.

Keep your SDK

If your code already uses another provider's library, change the base URL and the key and keep the rest. Only sending is emulated; the details per provider are in the migration guides (SendGrid, Mailgun, Postmark, Resend).

Node.js
// Resend SDK: it reads the base URL from the environment.
// RESEND_BASE_URL=https://api.hermaily.com
const { Resend } = require("resend");
const resend = new Resend(process.env.HERMAILY_API_KEY);

// Postmark:
const client = new postmark.ServerClient(process.env.HERMAILY_API_KEY, { requestHost: "api.hermaily.com" });

// mailgun.js:
const mg = new Mailgun(FormData).client({ username: "api", key: process.env.HERMAILY_API_KEY, url: "https://api.hermaily.com" });

Events and webhooks

Every message gets an id: over the API it comes in the 202 response and over SMTP it comes in the server's reply to the message (250 2.0.0 Ok: queued as <id>). Accepted means queued, not delivered. To know what happened next:

  • Dashboard. Messages lists each message with its events: delivered, deferred, bounced, complaint, opened, clicked.
  • API. GET https://api.hermaily.com/v1/messages/{id} returns the current status and every event, oldest first (see looking up a message).
  • Webhooks. In Webhooks, add your URL (https and public) and the events you want. Hermaily makes one POST per event, signed with X-Hermaily-Signature: t=<unix>,v1=<hex>, where v1 is HMAC-SHA256(secret, t + "." + body) over the raw body. Answer any 2xx within 10 seconds; otherwise it is retried for about a day and a half. Delivery is at least once, so discard duplicates by the event id. The Test button sends a sample event to check your receiver.

A receiver that checks the signature:

Node.js · Express
import crypto from "node:crypto";

export function verifyHermaily(rawBody, header, secret, tolerance = 300) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const t = Number(parts.t);
  if (!t || Math.abs(Date.now() / 1000 - t) > tolerance) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.`).update(rawBody).digest("hex");
  const a = Buffer.from(expected), b = Buffer.from(parts.v1 ?? "");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// Express: the route needs the unparsed body.
app.post("/webhooks/hermaily", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyHermaily(req.body, req.get("X-Hermaily-Signature") ?? "", process.env.HERMAILY_WEBHOOK_SECRET)) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body);
  // event.type: "delivery", "bounce", "complaint"...; queue the work, discard duplicates by event.id
  res.sendStatus(204);
});

Event types: send, delivery, delivery_delay, bounce, complaint, reject, rendering_failure, open, click and unsubscribe (opens and clicks only with tracking on). Permanent bounces, complaints and unsubscribes are suppressed automatically, so you do not need to keep your own list for that. Payload, fields and signature details are in the webhook documentation.

To check one message from code:

Node.js
const res = await fetch(`https://api.hermaily.com/v1/messages/${id}`, {
  headers: { Authorization: `Bearer ${process.env.HERMAILY_API_KEY}` },
});
const message = await res.json(); // status: "delivered", "bounced"...; events: [...]

Troubleshooting

The errors you are most likely to see, with what they mean. The full list is in errors and limits.

401 unauthorized

The key is missing, mistyped or revoked. Send it as Authorization: Bearer hm_... and check that the environment variable is really set where the code runs.

403 forbidden

The account cannot send yet (pending approval, paused, or new terms to accept), the key is restricted to the other stream, the From address is not on the key's domain, or the plan does not include broadcasts. GET https://api.hermaily.com/v1/domain tells you the key's domain, whether it is verified and whether the account can send.

422 validation

Sender domain not verified, empty subject, no recipient, more recipients than the plan allows, an invalid address or base64, or a message that is too large. The message says which; it follows Accept-Language (Spanish by default, so send Accept-Language: en). Code against code, not the text.

535 5.7.8: authentication failed

The password must be the whole API key (hm_...), copied without spaces and not revoked. The username can be anything; use apikey. After many failed attempts from the same IP, logins are refused for a few minutes.

The connection hangs or times out

Your host blocks outgoing SMTP. Try port 465 with implicit TLS instead of 587. If both are closed, use the HTTP API with fetch, which goes over port 443.

Send your first message today

Create the account, verify your domain and paste the key. The free plan is enough to try it.

Create a free account