1. Install the SDK
The SDK is a thin TypeScript client with no runtime dependencies — it uses the platform’s own fetch and Uint8Array, so it runs in Node 18+, Cloudflare Workers, Bun, Deno and the browser. Nothing is deployed into your account.
# The official SDK — one dependency, no runtime deps of its own.
pnpm add @flowmails/flowmails-sdk
# or
npm install @flowmails/flowmails-sdk
# Nothing else to install: the mailbox, the worker, the database and
# the dashboard are hosted by Flowmails. There is no Worker to deploy
# and no D1 database to provision.
2. Set FLOWMAILS_API_KEY
Mint a key in Settings → API Keys and put it in an environment variable. The key is pinned to one of your domains: a send() whose from lands on any other domain is refused with a 422 from_domain_mismatch, so a leaked key cannot impersonate your other domains. The raw key is shown once, at creation; only a hash is stored, so store it in your secret manager. Never commit it.
# .env — never commit this file
FLOWMAILS_API_KEY=fm_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# The endpoint's signing secret, from Settings → Webhooks (step 5)
FLOWMAILS_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxx
3. Initialize the client
One constructor, one credential. The client holds the key in memory for its lifetime — no disk cache, no logging of the token — and points at the hosted API by default.
import { Flowmails } from "@flowmails/flowmails-sdk";
const fm = new Flowmails({
// Required. Mint it at /dashboard/developers/api-keys — it is bound to
// ONE of your domains, so a leaked key cannot send as another.
apiKey: process.env.FLOWMAILS_API_KEY!,
// Optional. Defaults to the hosted API; override for a staging host.
// baseURL: "https://sdk.flowmails.net",
// Optional. Transient failures (5xx / 408 / 429 / network) are
// retried this many times with exponential backoff. Default 2.
// maxRetries: 2,
});
4. Send a message
fm.send() posts to POST /api/v1/messages. The answer carries the SMTP Message-ID every read path takes, and a verdict over every recipient — a send the relay refused is still an HTTP 201, with status: "failed" and the relay’s own reason. Sending is optional per domain: a domain with no outbound provider answers 409 sending_not_configured before dispatch instead of burning a quota slot.
const result = await fm.send({
from: "support@yourdomain.com", // must be on the key's bound domain
to: "customer@example.com", // string or string[]
subject: "Order #1234 confirmed",
text: "Thanks for your order — we will ship it tomorrow.",
// html: "<p>Thanks for your order…</p>",
// One key per logical mail: a retry with the same key replays the
// first answer instead of sending a second message.
idempotencyKey: "order-1234",
});
console.log(result);
// {
// id: "8421", // row id (string)
// status: "sent", // sent | partial | failed
// messageId: "<CAF…@yourdomain.com>", // SMTP Message-ID
// sendFeedback: null, // the relay's own words
// error: null, // "send_failed" on a refusal
// recipients: [{ address: "customer@example.com", status: "sent" }],
// }
// A 201 is not the same thing as "delivered": the relay can refuse a
// send, and it can refuse SOME of several recipients. Check before
// treating the response as success.
if (result.error) {
console.error("refused:", result.error, result.sendFeedback);
}
No SDK? The same request with plain fetch returns the same body — the SDK only adds typed payloads, typed errors and the retry policy.
// Prefer plain fetch? Same endpoint, same header, no dependency:
const res = await fetch("https://sdk.flowmails.net/api/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.FLOWMAILS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "support@yourdomain.com",
to: "customer@example.com",
subject: "Order #1234 confirmed",
text: "Thanks for your order — we will ship it tomorrow.",
}),
});
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
console.log(await res.json()); // the same object the SDK returns
5. Read email
There is no schema to apply and no local database: the mailbox is hosted and already scoped to your account. Search returns hits (addressing, subject, preview); the body is fetched per message with fm.messages.get(). fm.events.list() tails the same mail as routing facts, keyed on an event-id cursor rather than a timestamp.
// 1. Resolve the domain's id — the read paths take the id, not the
// domain name.
const domains = await fm.addresses.listDomains();
const domain = domains.find((d) => d.name === "yourdomain.com");
if (!domain) throw new Error("add the domain to Flowmails first");
// 2. Search its mailbox.
const hits = await fm.messages.search(domain.id, {
q: "invoice",
limit: 10, // optional — default 20
field: "subject", // optional — subject | from | to | body
});
console.log(hits.total, hits.messages.map((m) => m.subject));
// A hit is addressing + subject + preview. The body is fetched per
// message, never returned by a search.
// 3. Fetch the one message you care about — by its SMTP Message-ID.
const message = await fm.messages.get(hits.messages[0].messageId);
console.log(message.from, message.subject);
console.log(message.text); // plain text — regex a code out of this
console.log(message.attachments); // [{ filename, mimeType, size, url }]
// 4. Tail the event log instead of polling the mailbox: a cursor over
// routing facts plus the subject, never a body.
let cursor: string | undefined;
const page = await fm.events.list({ after: cursor, limit: 50 });
for (const event of page.events) {
console.log(event.event, event.recipient, event.subject);
}
cursor = page.nextCursor; // persist this, not a timestamp
# The same read paths over HTTP, if you are not using the SDK.
# domainId is the domain's id (GET /api/agent/domains lists them),
# not the domain name.
curl "https://sdk.flowmails.net/api/agent/emails/search?domainId=<domain-id>&q=invoice&limit=10" \
-H "Authorization: Bearer $FLOWMAILS_API_KEY"
curl "https://sdk.flowmails.net/api/agent/messages/<Message-ID>" \
-H "Authorization: Bearer $FLOWMAILS_API_KEY"
6. Receive mail events
Two shapes, one mailbox. A durable wait is the request/response form: it answers immediately and resolves when the mail lands. A signed webhook is the push form: register an endpoint in Settings → Webhooks and Flowmails POSTs message.received, message.sent or wait.resolved to it. Delivery is at-least-once, so verify the signature and dedupe on the delivery id.
// A durable wait answers immediately and resolves when the mail lands.
// Nothing holds a request open, and the wait survives a restart — the
// pattern for a verification code, a reply, or any step where a polling
// loop would burn tokens.
const wait = await fm.waits.create({
address: "support@yourdomain.com", // the mailbox to watch
subject: "Re: Order #1234", // optional — subject substring
timeoutMs: 5 * 60 * 1000, // optional — default 15 min, cap 24h
});
// { waitId: "wait_…", pollAfterMs: 2000, status: "pending", … }
let state = await fm.waits.get(wait.waitId);
while (state.status === "pending") {
await new Promise((r) => setTimeout(r, wait.pollAfterMs));
state = await fm.waits.get(wait.waitId);
}
if (state.status === "resolved") {
const mail = await fm.messages.get(state.resolvedMessageId!);
console.log("the reply:", mail.subject);
}
// Receiving side — a Node server, a Worker, a Lambda, anything that
// speaks fetch. Flowmails POSTs a signed event to the URL you register
// in the dashboard; it retries up to 5 times with backoff, so the same
// delivery can arrive twice. Dedupe on X-Flowmails-Delivery-Id.
const TOLERANCE_SECONDS = 300; // how far a sender's clock may drift
// Constant-time compare: a byte-by-byte === returns early on the first
// mismatch and leaks how much of the signature matched.
function timingSafeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
async function signatureIsValid(
raw: string,
timestamp: string | null,
header: string | null,
secret: string,
): Promise<boolean> {
if (!header?.startsWith("sha256=")) return false;
if (!timestamp || !/^\d+$/.test(timestamp)) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) {
return false;
}
// The signed material is `<timestamp>.<raw body>` — the timestamp is
// INSIDE the signature, so a captured request cannot be replayed with
// a fresh header. Sign the bytes as received: re-serialising the JSON
// changes them and the signature stops matching.
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const mac = await crypto.subtle.sign(
"HMAC",
key,
new TextEncoder().encode(`${timestamp}.${raw}`),
);
const expected = [...new Uint8Array(mac)]
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return timingSafeEqual(expected, header.slice("sha256=".length));
}
export async function POST(request: Request): Promise<Response> {
const raw = await request.text();
const ok = await signatureIsValid(
raw,
request.headers.get("x-flowmails-timestamp"),
request.headers.get("x-flowmails-signature"),
process.env.FLOWMAILS_WEBHOOK_SECRET!,
);
if (!ok) return new Response("bad signature", { status: 401 });
const payload = JSON.parse(raw) as {
id: string;
event: "message.received" | "message.sent" | "wait.resolved";
data: { messageId?: string; recipient?: string; subject?: string | null };
};
if (payload.event === "message.received" && payload.data.messageId) {
// The payload carries routing facts and the subject — never the
// body. Fetch it with the id it names.
const message = await fm.messages.get(payload.data.messageId);
await enqueueForSupport(message);
}
// 2xx acknowledges. A non-2xx schedules a retry.
return Response.json({ ok: true });
}
Full contract — the four headers, the HMAC algorithm, the retry ladder and the delivery log — on the webhooks page.
7. Errors and retries
Every failure is a subclass of FlowmailsError, so instanceof is the branch. The client retries transient failures automatically — HTTP 5xx, 408, 429 and network errors, with exponential backoff, maxRetries times (default 2). A retry is only safe for a send when you pass an idempotency key: the retry then replays the first answer instead of sending twice.
import {
FlowmailsError,
AuthenticationError,
ValidationError,
RateLimitError,
UpstreamError,
} from "@flowmails/flowmails-sdk";
try {
await fm.send({ from, to, subject, text });
} catch (err) {
if (err instanceof AuthenticationError) {
// 401 — the key is missing, malformed or revoked. Fix the
// credential; a retry sends the same rejected request.
console.error("check FLOWMAILS_API_KEY", err.code);
} else if (err instanceof ValidationError) {
// 400 / 404 / 409 / 422 — the payload or the configuration is
// wrong (from-address not on the key's domain, no sending
// provider, an idempotency key reused for a different body).
console.error(err.code, err.detail);
} else if (err instanceof RateLimitError) {
// 429 — the send quota. Do NOT hammer it; read resetAt.
console.error("quota", err.limit, err.remaining, err.resetAt);
} else if (err instanceof UpstreamError) {
// 5xx / 408 / network — the SDK already retried maxRetries
// times. Back off and retry later.
console.error("upstream", err.code, err.status);
} else if (err instanceof FlowmailsError) {
console.error(err.code, err.status, "retryable:", err.retryable);
} else {
throw err;
}
}
8. Complete example
One file, runnable with node --env-file=.env main.mjs: send, read the outbox back, then wait for the reply and read it. Replace yourdomain.com with a domain you added to Flowmails.
import { Flowmails, FlowmailsError } from "@flowmails/flowmails-sdk";
const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
const DOMAIN = "yourdomain.com";
const MAILBOX = `support@${DOMAIN}`;
// 1. Send a message. A refused send is a 201 with `error` set, so
// check the body — not just the promise.
async function send(reason: string) {
const result = await fm.send({
from: MAILBOX,
to: "customer@example.com",
subject: `Order #1234 — ${reason}`,
text: "Thanks for your order — we will ship it tomorrow.",
idempotencyKey: `order-1234-${reason}`,
});
if (result.error) {
throw new Error(`send refused: ${result.sendFeedback ?? result.error}`);
}
return result;
}
// 2. Read the message back through the mailbox search.
async function findSent(messageId: string) {
const domains = await fm.addresses.listDomains();
const domain = domains.find((d) => d.name === DOMAIN)!;
const hits = await fm.messages.search(domain.id, {
q: "Order #1234",
field: "subject",
type: "send",
});
return hits.messages.find((m) => m.messageId === messageId);
}
// 3. Wait for the reply, then read its body.
async function waitForReply() {
const wait = await fm.waits.create({
address: MAILBOX,
subject: "Re: Order #1234",
timeoutMs: 60_000,
});
for (;;) {
const state = await fm.waits.get(wait.waitId);
if (state.status === "resolved" && state.resolvedMessageId) {
return fm.messages.get(state.resolvedMessageId);
}
if (state.status === "expired") return null;
await new Promise((r) => setTimeout(r, wait.pollAfterMs));
}
}
async function main() {
const sent = await send("confirmed");
console.log("sent", sent.messageId, sent.status);
console.log("in the outbox:", await findSent(sent.messageId));
const reply = await waitForReply();
console.log(reply ? `reply: ${reply.subject}\n${reply.text}` : "no reply yet");
}
main().catch((err) => {
// The typed classes are the contract; branch on the class first, then
// on `code` when you need finer discrimination.
if (err instanceof FlowmailsError) {
console.error(err.name, err.code, err.status, "retryable:", err.retryable);
process.exitCode = 1;
return;
}
throw err;
});