Send with

Send email with Cloudflare Workers

Workers can call any HTTPS API with fetch. Keep the API key in a secret, and use ctx.waitUntil() so the visitor gets a response before the email call finishes.

Store the key as a secret

npx wrangler secret put ROBUSTEMAIL_API_KEY

For local development, put it in .dev.vars:

# .dev.vars (do not commit)
ROBUSTEMAIL_API_KEY=rb_test_...

The Worker

// src/index.ts
interface Env {
  ROBUSTEMAIL_API_KEY: string;
}

async function sendEmail(env: Env, email: Record<string, unknown>, idempotencyKey?: string): Promise<string> {
  const res = await fetch("https://robustemail.com/api/v2/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${env.ROBUSTEMAIL_API_KEY}`,
      "Content-Type": "application/json",
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: JSON.stringify(email),
  });

  const body = await res.json<{ id?: string; name?: string; message?: string }>();
  if (!res.ok) {
    throw new Error(`${body.name}: ${body.message}`);
  }
  return body.id!;
}

export default {
  async fetch(request, env, ctx): Promise<Response> {
    const url = new URL(request.url);
    if (request.method !== "POST" || url.pathname !== "/contact") {
      return new Response("Not found", { status: 404 });
    }

    const { email, message } = await request.json<{ email: string; message: string }>();

    // Reply now; the email call finishes in the background
    ctx.waitUntil(
      sendEmail(env, {
        from: "Acme Website <website@acme.com>",
        to: "team@acme.com",
        reply_to: email,
        subject: "New contact form message",
        text: message,
      }).catch((err) => console.error("Email failed", err)),
    );

    return Response.json({ ok: true }, { status: 202 });
  },
} satisfies ExportedHandler<Env>;

Run npx wrangler types to generate the ExportedHandler types for your project.

When the email must not be lost

waitUntil does not retry. For important email, send a message to a Cloudflare Queue and call the API from the queue consumer with a stable idempotency key: retries then never send twice.

Next