Send Email from Cloudflare Workers
Pranav Patel
Co-founder·9 min read
On this page

Send transactional email from Cloudflare Workers with Reloop: a plain fetch call or the SDK with nodejs_compat, secrets with Wrangler, waitUntil, retries with Idempotency-Key, Queues and Cron Triggers.
To send email from a Cloudflare Worker, call Reloop's HTTP API with fetch. Workers can't hold a normal SMTP connection, but they're very good at HTTP. One POST to https://reloop.sh/api/mail/v1/send with your API key in an x-api-key header sends the email. No SDK is required, and if you'd like one, the reloop-email package works too with the nodejs_compat flag.
This guide covers both options, plus the parts that matter in production: secrets, sending without slowing down the response, safe retries, Queues and scheduled sends.
Using a framework on top of Workers? The SvelteKit, Remix and Next.js guides use the same API.
Why HTTP and not SMTP
Most email libraries for Node (Nodemailer, for example) open a TCP connection to an SMTP server. That doesn't fit the Workers runtime:
- Workers run on V8 isolates, not a full Node.js process, so many Node networking APIs aren't available.
- Every request should finish fast. An SMTP handshake with STARTTLS adds several round trips.
- An HTTP API gives you a single request, a JSON response with an email ID, and structured errors.
So the pattern on Workers is simple: HTTP out, Reloop does the SMTP.
fetch to the REST APIreloop-email SDKnodejs_compatPrerequisites
- A Cloudflare account and Wrangler (
npm create cloudflare@latestsets up a project). - A Reloop API key from the dashboard. Keys start with
rl_. - A verified sending domain. See connect a domain and the SPF, DKIM and DMARC guide.
1. Store the API key as a secret
Never put the key in wrangler.jsonc or in your source. Use a Worker secret:
npx wrangler secret put RELOOP_API_KEYPaste the key when prompted. For local development with wrangler dev, put it in .dev.vars (and add that file to .gitignore):
RELOOP_API_KEY=rl_your_api_key_hereSecrets show up on the env object passed to your handler, so type them once:
1export interface Env {2 RELOOP_API_KEY: string;3}2. Option A: plain fetch (no dependencies)
This is the whole integration:
1import type { Env } from "./env";2
3export type SendEmailInput = {4 from: string;5 to: string | string[];6 subject: string;7 html?: string;8 text?: string;9 reply_to?: string;10 tags?: { name: string; value: string }[];11};12
13export type SendEmailResult =14 | { ok: true; id: string; messageId: string }15 | { ok: false; status: number; code?: string; message: string };16
17export async function sendEmail(18 env: Env,19 input: SendEmailInput,20 idempotencyKey?: string,21): Promise<SendEmailResult> {22 const headers: Record<string, string> = {23 "x-api-key": env.RELOOP_API_KEY,24 "Content-Type": "application/json",25 };26 if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;27
28 const res = await fetch("https://reloop.sh/api/mail/v1/send", {29 method: "POST",30 headers,31 body: JSON.stringify(input),32 });33
34 if (!res.ok) {35 const body = (await res.json().catch(() => ({}))) as {36 code?: string;37 message?: string;38 };39 return {40 ok: false,41 status: res.status,42 code: body.code,43 message: body.message ?? res.statusText,44 };45 }46
47 const data = (await res.json()) as { id: string; messageId: string };48 return { ok: true, id: data.id, messageId: data.messageId };49}And a Worker that uses it:
1import type { Env } from "./env";2import { sendEmail } from "./reloop";3
4export default {5 async fetch(request, env): Promise<Response> {6 if (request.method !== "POST") {7 return new Response("Method not allowed", { status: 405 });8 }9
10 const { email } = (await request.json()) as { email?: string };11 if (!email || !email.includes("@")) {12 return Response.json({ error: "Invalid email" }, { status: 400 });13 }14
15 const result = await sendEmail(env, {16 from: "Acme <hello@mail.acme.com>",17 to: email,18 subject: "Welcome to Acme",19 html: "<p>Thanks for signing up.</p>",20 text: "Thanks for signing up.",21 tags: [{ name: "type", value: "welcome" }],22 });23
24 if (!result.ok) {25 console.error("Reloop send failed", result);26 return Response.json({ error: "Could not send email" }, { status: 502 });27 }28
29 return Response.json({ ok: true, id: result.id });30 },31} satisfies ExportedHandler<Env>;Reloop also accepts Authorization: Bearer rl_… if you prefer that header style. Both work.
What the response looks like
A successful send returns the email's ID and the SMTP message ID:
1{2 "success": true,3 "id": "em_…",4 "messageId": "<…@mail.acme.com>",5 "status": "sent",6 "timestamp": "2026-04-21T10:00:00.000Z"7}Errors are JSON with a stable code you can branch on, plus message, why, fix and a docs link:
1{2 "code": "not_found",3 "message": "Domain not found",4 "why": "The domain acme.com was not found or is not authorized for your organization",5 "fix": "Ensure the domain is registered and verified in your dashboard",6 "link": "https://reloop.sh/docs/api/errors"7}The full list of codes is in the errors reference.
3. Option B: the reloop-email SDK
The Node SDK uses the global fetch, so it runs on Workers. It also bundles webhook signature helpers that import Node's crypto module, which means you need Cloudflare's Node.js compatibility flag.
npm install reloop-emailEnable the flag in wrangler.jsonc:
1{2 "name": "acme-mailer",3 "main": "src/index.ts",4 "compatibility_date": "2026-04-15",5 "compatibility_flags": ["nodejs_compat"]6}Then create the client inside the handler, because secrets only exist on env:
1import { Reloop } from "reloop-email";2import type { Env } from "./env";3
4export default {5 async fetch(request, env): Promise<Response> {6 const reloop = new Reloop({ apiKey: env.RELOOP_API_KEY });7
8 const { response, emailError } = await reloop.mail.send({9 from: "Acme <hello@mail.acme.com>",10 to: "user@example.com",11 subject: "Your receipt",12 html: "<p>Thanks for your order.</p>",13 text: "Thanks for your order.",14 });15
16 if (emailError) {17 console.error(emailError.status, emailError.message);18 return Response.json({ error: "Could not send email" }, { status: 502 });19 }20
21 return Response.json({ ok: true, id: response.id });22 },23} satisfies ExportedHandler<Env>;The SDK never throws for API errors. It returns { response, emailError }, and emailError carries the HTTP status, message and the full error body.
4. Don't make the user wait: ctx.waitUntil
Sending a welcome email shouldn't add latency to a signup request. Workers let you finish background work after the response is sent with ctx.waitUntil:
1export default {2 async fetch(request, env, ctx): Promise<Response> {3 const { email } = (await request.json()) as { email: string };4
5 const user = await createUser(env, email);6
7 ctx.waitUntil(8 sendEmail(env, {9 from: "Acme <hello@mail.acme.com>",10 to: user.email,11 subject: "Welcome to Acme",12 html: "<p>You're in.</p>",13 }).then((r) => {14 if (!r.ok) console.error("welcome email failed", r);15 }),16 );17
18 return Response.json({ ok: true });19 },20} satisfies ExportedHandler<Env>;waitUntil keeps the Worker alive until the promise settles, but it doesn't retry. For anything you can't afford to lose, use a Queue (next section).
5. Retry safely with Idempotency-Key
Networks fail. If a fetch times out you don't know whether Reloop received it. Retrying blindly could send the same password reset twice.
Send an Idempotency-Key header and retries become safe. Reloop stores a successful response for 24 hours, and a repeat request with the same key and body returns the original result instead of sending again.
1const key = `password-reset:${user.id}:${resetToken}`;2
3for (let attempt = 0; attempt < 3; attempt++) {4 const result = await sendEmail(env, message, key);5 if (result.ok) break;6 if (result.status < 500 && result.status !== 429) break; // don't retry 4xx7 await new Promise((r) => setTimeout(r, 2 ** attempt * 500));8}422More in the idempotency docs.
6. Durable sends with Cloudflare Queues
For high-volume or must-deliver email, put the message on a Cloudflare Queue and send it from a consumer. Queues retry failed messages for you.
1{2 "queues": {3 "producers": [{ "binding": "EMAIL_QUEUE", "queue": "emails" }],4 "consumers": [{ "queue": "emails", "max_retries": 5 }]5 }6}1import type { SendEmailInput } from "./reloop";2import { sendEmail } from "./reloop";3
4interface Env {5 RELOOP_API_KEY: string;6 EMAIL_QUEUE: Queue<{ key: string; message: SendEmailInput }>;7}8
9export default {10 async fetch(request, env): Promise<Response> {11 const { email } = (await request.json()) as { email: string };12
13 await env.EMAIL_QUEUE.send({14 key: crypto.randomUUID(),15 message: {16 from: "Acme <hello@mail.acme.com>",17 to: email,18 subject: "Your invoice is ready",19 html: "<p>Download it from your dashboard.</p>",20 },21 });22
23 return Response.json({ queued: true });24 },25
26 async queue(batch, env): Promise<void> {27 for (const msg of batch.messages) {28 const result = await sendEmail(env, msg.body.message, msg.body.key);29 if (result.ok || (result.status < 500 && result.status !== 429)) {30 msg.ack();31 } else {32 msg.retry();33 }34 }35 },36} satisfies ExportedHandler<Env, { key: string; message: SendEmailInput }>;The idempotency key travels with the message, so a retried queue message never turns into a duplicate email.
7. Scheduled email with Cron Triggers
Daily digests and reminders fit Cron Triggers:
1{2 "triggers": { "crons": ["0 9 * * 1"] }3}1export default {2 async scheduled(controller, env, ctx): Promise<void> {3 const users = await getUsersWantingDigest(env);4
5 for (const user of users) {6 ctx.waitUntil(7 sendEmail(8 env,9 {10 from: "Acme <digest@mail.acme.com>",11 to: user.email,12 subject: "Your weekly summary",13 html: renderDigest(user),14 },15 `digest:${user.id}:${controller.scheduledTime}`,16 ),17 );18 }19 },20} satisfies ExportedHandler<Env>;If you only need to send one email at a specific time, you don't need a cron at all: pass scheduled_at (an ISO 8601 timestamp) in the send request and Reloop holds it until then.
Production checklist
-
RELOOP_API_KEYset withwrangler secret put, never in config or code -
fromuses a domain verified in Reloop - Endpoint that triggers sends is authenticated or rate-limited (an open send endpoint is an open relay)
- User-facing sends use
ctx.waitUntilor a Queue - Retries send an
Idempotency-Key - 4xx errors are logged and not retried; 5xx and 429 are retried with backoff
- Plain-text
textincluded alongsidehtml
FAQ
Not reliably. Workers are built for HTTP, and SMTP needs a long-lived TCP session with STARTTLS. Use the HTTP API from Workers, and keep SMTP for servers and tools that only speak SMTP.
Only for the SDK. The plain fetch approach has no dependencies and runs
without any compatibility flags.
Yes. Pages Functions run on the same runtime. Read the key from
context.env.RELOOP_API_KEY and call the same sendEmail helper.
Yes. Replace https://reloop.sh with your instance's URL, or pass
baseUrl to the SDK. See self-hosting Reloop.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


