Skip to content

Documentation

Send email from a Cloudflare Worker.

A Worker that sends a message with fetch, with the key stored as a secret.

Before you start

You need a verified sending domain (see Domains) and an API key (under API keys in the dashboard; it is shown once). Keep the key in an environment variable on your server, never in code that runs in a browser or an app.

Store the key as a secret

Do not put the key in your configuration file. Store it as a secret, which Cloudflare keeps encrypted and gives your code as a binding.

Terminal
npx wrangler secret put MAILTRUSS_API_KEY

The Worker

The client uses fetch, which Workers provide, so nothing else is needed. waitUntil lets the send finish after the response, if you do not want to make the visitor wait for it.

src/index.ts
import { MailClient, MailError } from "mailtruss";
​
interface Env { MAILTRUSS_API_KEY: string }
​
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
const { email } = await request.json<{ email: string }>();
const mail = new MailClient({ apiKey: env.MAILTRUSS_API_KEY });
​
const send = mail.emails.send(
{ from: "Acme <hello@yourdomain.com>", to: email, subject: "Welcome to Acme", text: "Thanks for signing up." },
{ idempotencyKey: `welcome:${email}` }, // a retry sends nothing twice
).catch((e) => { if (!(e instanceof MailError)) throw e; console.error("mail failed", e.code, e.requestId); });
​
ctx.waitUntil(send); // finish the send after the response goes out
return Response.json({ queued: true }, { status: 202 });
},
};

Configuration

No binding entry is needed for a secret. A recent compatibility date is enough.

wrangler.jsonc
{
"name": "mailer",
"main": "src/index.ts",
"compatibility_date": "2026-10-01"
}

Try it without sending real mail

Send to delivered@mailtruss.test first. It works before any domain is verified and reaches no real mailbox, so you can check your code and see the recorded timeline. Then try bounced@mailtruss.test to see what a bounce looks like. All the test addresses are listed under Sending.

See what happened

Open the message under Emails in the dashboard: it shows the recorded timeline, what each event proves, and a diagnosis if something went wrong. Or fetch it with GET /api/v1/emails/:id/events. To be told as it happens, add a webhook.

If it fails

API requests answer with an error name and message. The common ones:

  • 403 invalid_api_key or 401 missing_api_key: the key is wrong, revoked or not sent. Send it as Authorization: Bearer ms_live_….
  • 403 domain_not_verified: the from address is on a domain that is not verified. Publish the DNS records and re-check.
  • 422 validation_error: fix the field the message names. Nothing was sent and no quota was used.
  • 429 rate_limit_exceeded: back off for the Retry-After header. See rate limits.

Problems that happen after a message is accepted (bounces, complaints) are explained under delivery errors.

Other guides

Last updated

Something wrong or unclear on this page?

Report an issue