Direct mail API for Cloudflare
Direct mail API for Cloudflare: a Worker takes a paid order and puts the postcard on a Queue, a Cron Trigger queues win-back batches every night, and the queue consumer sends each one to Mailr with a key stored as a Wrangler secret, retrying anything that fails.
What to mail from Cloudflare
| When this happens | Mail this |
|---|---|
| Your store or app POSTs a paid order to the Worker's /orders/paid route | A thank-you postcard for a first order. (First-order thank you) |
| The Cron Trigger 0 9 * * * fires (2:00 a.m. in Phoenix) | Win-back postcards to customers 60+ days past their last order, 250 per batch. (Win-back) |
| Your app POSTs a checkout that's still open after 48 hours | An abandoned-cart postcard with the product they left behind. Add a route like /orders/paid that queues it. (Abandoned cart) |
Set it up
- Create the queue. Run npx wrangler queues create mailr-send. If the dead-letter queue named in wrangler.toml doesn't exist, Cloudflare creates it for you.
- Store the secrets. Run npx wrangler secret put MAILR_API_KEY and paste your mlr_test_ key, then npx wrangler secret put INBOUND_SECRET with a random string your app sends as a Bearer token. Each secret put deploys a new version of the Worker. For local development, put both in .dev.vars and keep that file out of git.
- Add the Worker. Copy src/index.ts and wrangler.toml. The fetch handler and the Cron Trigger only put messages on the queue; the queue consumer is the one place that calls Mailr. Save your return address in Mailr's Settings so the messages can leave out from.
- Test locally. Run npx wrangler dev, POST a sample order to http://localhost:8787/orders/paid with your INBOUND_SECRET, and run the nightly job with curl "http://localhost:8787/cdn-cgi/local/scheduled". Test pieces show up in your Mailr dashboard and never print.
- Deploy and go live. Run npx wrangler deploy. A new or changed Cron Trigger can take up to 15 minutes to start firing. When the test pieces look right, run wrangler secret put MAILR_API_KEY again with your mlr_live_ key.
The Worker and its config
// src/index.ts: takes orders, queues win-back batches every night, and sends everything to Mailr from one queue consumer.
import { lapsedCustomers, markWinbackQueued } from "./customers"; // your data layer (D1, Hyperdrive or an API)
type Address = { name: string; line1: string; line2?: string; city: string; state: string; zip: string };
type MailrJob = { path: "/postcards" | "/flats" | "/batches"; idempotencyKey: string; body: Record<string, unknown> };
export interface Env {
MAILR_API_KEY: string; // wrangler secret put MAILR_API_KEY
INBOUND_SECRET: string; // wrangler secret put INBOUND_SECRET
MAILR_QUEUE: Queue<MailrJob>;
}
const PER_BATCH = 250; // a queue message is capped at 128 KB, so 250 recipients per Mailr batch, not 1,000
export default {
// Your app posts a paid order here. The Worker queues the postcard and answers right away.
async fetch(request, env) {
const url = new URL(request.url);
if (request.method !== "POST" || url.pathname !== "/orders/paid") return new Response("Not found", { status: 404 });
if (request.headers.get("authorization") !== `Bearer ${env.INBOUND_SECRET}`) return new Response("Unauthorized", { status: 401 });
const order = await request.json<{ id: string; firstName: string; shipTo: Address }>();
await env.MAILR_QUEUE.send({
path: "/postcards",
idempotencyKey: `thank-you-${order.id}`,
body: {
size: "6x9",
template: "tmpl_thank_you",
to: order.shipTo, // no "from": Mailr prints the return address saved in Settings
merge: { first_name: order.firstName.slice(0, 14) || "there", promo_code: "THANKS15" },
},
});
return Response.json({ queued: true });
},
// Cron Trigger "0 9 * * *" (UTC): queue tonight's win-back batches.
async scheduled(_controller, env) {
const people = await lapsedCustomers(env); // last order 60+ days ago, not queued yet
for (let i = 0; i < people.length; i += PER_BATCH) {
const chunk = people.slice(i, i + PER_BATCH);
// Same customers, same key: a repeated run can't mail them twice within 24 hours.
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(chunk.map((c) => c.id).join(",")));
const key = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
await env.MAILR_QUEUE.send({
path: "/batches",
idempotencyKey: `winback-${key}`,
body: {
kind: "postcard",
size: "6x11",
template: "tmpl_winback",
merge: { promo_code: "PEAK15" },
recipients: chunk.map((c) => ({ to: c.address, merge: { first_name: c.firstName, last_product: c.lastProduct } })),
},
});
await markWinbackQueued(env, chunk.map((c) => c.id));
}
},
// Queue consumer: the only code that calls Mailr.
async queue(batch, env) {
for (const msg of batch.messages) {
const job = msg.body;
try {
const res = await fetch(`https://api.mailr.dev/v1${job.path}`, {
method: "POST",
headers: {
Authorization: `Bearer ${env.MAILR_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": job.idempotencyKey,
},
body: JSON.stringify(job.body),
});
const data = await res.json<{ id?: string; error?: { message: string } }>();
if (res.ok || [400, 401, 404, 422].includes(res.status)) {
// Sent, or a request a retry can't fix: log it (store data.id where your app keeps it) and let it go.
console.log(JSON.stringify({ key: job.idempotencyKey, status: res.status, id: data.id, error: data.error?.message }));
msg.ack();
} else {
msg.retry({ delaySeconds: 60 * msg.attempts }); // 402, 409, 5xx: try again later
}
} catch {
msg.retry({ delaySeconds: 60 * msg.attempts }); // network error or a reply that isn't JSON
}
}
},
} satisfies ExportedHandler<Env, MailrJob>;- Cron Triggers run on UTC. 0 9 * * * is 2:00 a.m. in Phoenix all year, since Arizona doesn't change its clocks.
- A queue message can be at most 128 KB, so the cron handler sends batches of 250 recipients rather than Mailr's maximum of 1,000. Each batch is one request to Mailr and is all or nothing.
- The consumer retries a failed message up to max_retries times with a growing delay, then moves it to mailr-send-dlq. Without a dead-letter queue, messages that keep failing are discarded.
- A retried message carries the same Idempotency-Key, so if Mailr created the piece before the error, the retry gets that piece back instead of a second one.
- The Workers Free plan allows 5 Cron Triggers per account and 50 subrequests per invocation, and includes Queues with 10,000 operations a day. Scheduled Workers and queue consumers can run for up to 15 minutes of wall time.
What it costs
Each live piece is paid from your Mailr balance, printing and postage included: a 4x6 postcard is $0.85, a 6x9 $0.89 and an 8.5x11 letter $0.95 on pay as you go, less on a plan. Test pieces are free. All prices.
Templates that fit: First-order thank you (6x9), Win-back (6x11), Abandoned cart (6x9).
Questions
Why use a Queue instead of calling Mailr in the fetch handler?
The Worker can answer your store or app at once, and a failed request is retried later with a delay and kept in a dead-letter queue if it never goes through. Calling Mailr directly with fetch works too; send the same Idempotency-Key either way.
Can I put the key in wrangler.toml as a var?
No. Vars are plain text in a file you commit. Store the key with wrangler secret put, and the Worker reads it as env.MAILR_API_KEY like any other binding.
Does Mailr call my Worker back when a postcard is delivered?
Not yet. Mailr has no webhooks, so read GET /v1/postcards/{id} when you need a status, or list a batch's pieces with GET /v1/postcards?batch=bat_...
What does a nightly batch cost?
Each card in a batch is one piece at one price, printing and postage included: a 6x11 win-back card is $0.99 on pay as you go, less on a plan. Pieces made with a test key are free and never print.