Before you start
Three things from Hermaily before the first message:
- 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.
- 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.
- 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.
Configuration
Server-side variables in .env.local (and in your host's settings for production):
# .env.local (server only: no NEXT_PUBLIC_ prefix)
HERMAILY_API_KEY=hm_your_api_key
HERMAILY_WEBHOOK_SECRET=hmwh_your_webhook_secret
MAIL_FROM="Acme <hello@acme.example>"A variable without the NEXT_PUBLIC_ prefix is only available on the server. The helper below imports server-only (npm install server-only) so the build fails if a client component ever imports it.
Send a message
// lib/hermaily.ts
import "server-only";
type Email = {
to: string | string[];
subject: string;
html?: string;
text?: string;
reply_to?: string;
tags?: string[];
metadata?: Record<string, string>;
};
export async function sendEmail(email: Email) {
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, ...email }),
});
if (res.status !== 202) {
throw new Error(`Hermaily ${res.status}: ${await res.text()}`);
}
return (await res.json()) as { id: string; status: "queued" | "held" | "suppressed" };
}From a server action
// app/orders/actions.ts
"use server";
import { sendEmail } from "@/lib/hermaily";
import { getOrder } from "@/lib/orders"; // your own data access
export async function confirmOrder(orderId: string) {
const order = await getOrder(orderId);
const { id } = await sendEmail({
to: order.email,
subject: `Order ${order.number} confirmed`,
text: `Thanks for your order ${order.number}.`,
tags: ["order-confirmation"],
metadata: { order_id: order.id },
});
return { messageId: id };
}From a route handler
A contact form that writes to your team. Send to addresses you control or to your signed-in users; an endpoint that mails whatever address it receives will be abused.
// app/api/contact/route.ts: the contact form writes to your team, never to an address the visitor chooses.
import { sendEmail } from "@/lib/hermaily";
export async function POST(req: Request) {
const { email, message } = await req.json();
if (typeof email !== "string" || typeof message !== "string" || message.length > 5000) {
return Response.json({ error: "invalid" }, { status: 400 });
}
await sendEmail({
to: "support@acme.example",
reply_to: email,
subject: "New message from the contact form",
text: message,
tags: ["contact-form"],
});
return new Response(null, { status: 204 });
}Already on the Resend SDK
Already using the resend package? It reads its base URL from RESEND_BASE_URL: set it to https://api.hermaily.com, pass your Hermaily key and keep your calls. Other SDKs are in the Node.js guide and the details in migrate from Resend.
Events and webhooks
Every message gets an id: over the API it comes in the 202 response. 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
POSTper event, signed withX-Hermaily-Signature: t=<unix>,v1=<hex>, wherev1isHMAC-SHA256(secret, t + "." + body)over the raw body. Answer any2xxwithin 10 seconds; otherwise it is retried for about a day and a half. Delivery is at least once, so discard duplicates by the eventid. The Test button sends a sample event to check your receiver.
A route handler that verifies the signature over the raw body (it needs the Node.js runtime for node:crypto):
// app/api/webhooks/hermaily/route.ts
import crypto from "node:crypto";
export const runtime = "nodejs";
function verify(raw: Buffer, header: string, secret: string, 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(raw).digest("hex");
const a = Buffer.from(expected), b = Buffer.from(parts.v1 ?? "");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
export async function POST(req: Request) {
const raw = Buffer.from(await req.arrayBuffer()); // the bytes as they arrived
const header = req.headers.get("x-hermaily-signature") ?? "";
if (!verify(raw, header, process.env.HERMAILY_WEBHOOK_SECRET!)) {
return new Response("invalid signature", { status: 401 });
}
const event = JSON.parse(raw.toString("utf8"));
// event.type: "delivery", "bounce", "complaint"...; discard duplicates by event.id
return new Response(null, { status: 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.
Troubleshooting
The errors you are most likely to see, with what they mean. The full list is in errors and limits.
HERMAILY_API_KEY is undefined in production
Variables in .env.local are not deployed: add them in your host's environment settings and redeploy. The result is a 401 unauthorized.
The webhook signature never matches
The signature is computed over the bytes as they arrived. Read req.arrayBuffer() (or req.text()) before anything else and do not call req.json() first; check that HERMAILY_WEBHOOK_SECRET is the webhook's secret (hmwh_...), not the API key.
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.
429 rate_limited or 402 quota_exceeded
429 is the per-minute limit or a new account's warm-up: wait and retry with a growing delay (there is no Retry-After). 402 is the Free plan's monthly quota, used up until next month or until you upgrade. 500 internal is safe to retry.
Send your first message today
Create the account, verify your domain and paste the key. The free plan is enough to try it.