Frameworks

How to send email from Cloudflare Workers

Short answer

The simplest way to send email from a Cloudflare Worker is a fetch request to an email API, with the API key stored as a Worker secret. Workers block outbound connections on port 25, and common Node SMTP libraries such as Nodemailer do not run there, so SMTP is awkward. Cloudflare also has its own Email Service with a send_email binding. Use ctx.waitUntil to send without delaying the response.

Last checked 16 November 2026

To send email from a Cloudflare Worker, make a fetch request to an email API and keep the API key in a Worker secret. That is a few lines of code with no dependencies. SMTP is the awkward route on Workers: port 25 is blocked, and popular Node SMTP libraries do not run there. This guide shows the fetch approach, how to send in the background, and when Cloudflare’s own sending is worth a look.

Why not SMTP from a Worker?

According to Cloudflare’s TCP sockets docs, Workers cannot create outbound TCP connections on port 25. The connect() API can reach other ports, including the SMTP submission ports 465 and 587, but you would need an SMTP client written against Workers sockets. Nodemailer and other libraries built on Node’s net and tls modules do not work in that model, and every request would pay for a fresh SMTP handshake.

An email API is a better fit for an edge runtime: one HTTPS request per email, which fetch already handles.

Step 1: store the API key as a secret

npx wrangler secret put MAILCANDOR_KEY

Wrangler prompts for the value and stores it encrypted. It reaches your code as env.MAILCANDOR_KEY. For local development with wrangler dev, put it in a .dev.vars file (and add that file to .gitignore):

MAILCANDOR_KEY=mc_live_...

Never put the key in wrangler.toml or wrangler.jsonc under vars; those are plain text and end up in your repository.

Step 2: send with fetch

This Worker accepts a contact form post and sends it to your team through Mailcandor. Other email APIs follow the same pattern.

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

async function sendEmail(env: Env, email: Record<string, unknown>, key?: string) {
  const headers: Record<string, string> = {
    Authorization: `Bearer ${env.MAILCANDOR_KEY}`,
    'Content-Type': 'application/json',
  };
  if (key) headers['Idempotency-Key'] = key;

  const res = await fetch('https://api.mailcandor.com/v1/emails', {
    method: 'POST',
    headers,
    body: JSON.stringify(email),
  });
  if (!res.ok) {
    const { error } = await res.json<{ error: { type: string; message: string } }>();
    throw new Error(`${error.type}: ${error.message}`);
  }
  return res.json<{ id: string; status: string }>();
}

export default {
  async fetch(request, env, ctx): Promise<Response> {
    if (request.method !== 'POST') {
      return new Response('Method not allowed', { status: 405 });
    }

    const form = await request.formData();
    const email = form.get('email');
    const message = form.get('message');
    if (typeof email !== 'string' || typeof message !== 'string' || !message.trim()) {
      return new Response('Missing fields', { status: 400 });
    }

    ctx.waitUntil(
      sendEmail(env, {
        from: 'Acme website <hello@acme.com>',
        to: 'team@acme.com',
        reply_to: email,
        subject: 'New contact form message',
        text: message,
      }).catch((err) => console.error('email failed', err)),
    );

    return new Response('Thanks, we will be in touch.');
  },
} satisfies ExportedHandler<Env>;

ctx.waitUntil lets the Worker return the response straight away and keeps running until the email request finishes. Without it, the work could be cancelled once the response is sent. Errors inside it never reach the visitor, so the .catch logs them; read them with wrangler tail or in Workers Logs.

If the sender must know whether the email was accepted, await sendEmail(...) before responding instead. The API returns in well under a second with {"id": "...", "status": "queued"}.

Make sends safe to retry

The optional key argument becomes an Idempotency-Key header. Use a value that identifies the email, such as order-1042-receipt. If a Worker or a queue consumer runs twice, the second request returns the first response instead of sending a duplicate.

For high volume or work that must not be lost, put emails on a Cloudflare Queue and send from the queue consumer. Queues retry failed messages, and the idempotency key makes those retries harmless. Batch sending also helps here: POST /v1/emails/batch takes up to 100 emails per request, without attachments or scheduling.

Rate limits

Email APIs limit requests per second. On Mailcandor the limit is per team (5 a second on Starter, 10 on Pay as you go, 50 on Team), and every response carries ratelimit-* headers. A Worker that fans out to many recipients at once can hit that quickly; batch requests and a queue keep you under it.

Cloudflare’s own options

Cloudflare has two email products that sound similar:

  • Email Routing handles incoming mail. It forwards messages sent to your domain to another inbox or hands them to an Email Worker. It does not send your app’s outgoing email.
  • Email Service sends email through a send_email binding in Workers, a REST API or SMTP, from domains verified on Cloudflare. See the send email docs for its limits and current status.

A third-party email API is the more portable choice if your code may also run outside Cloudflare, or if you want features such as webhooks for every delivery event. The fetch code above runs unchanged in Node, Deno and Bun.

Before you send: verify your domain

Your sending domain needs SPF, DKIM and DMARC records, or mail will often land in spam. If the domain’s DNS is on Cloudflare, add the records your email provider gives you in the DNS tab, and set them to DNS only (grey cloud) where the record type allows proxying. The SPF, DKIM and DMARC setup guide explains each one.

Sending with Mailcandor

Mailcandor’s email API works from Workers with plain fetch; there is no SDK to bundle. Delivery, bounce and complaint events arrive as webhooks, which another Worker route can receive. Access is by request through the pricing page.

Questions

Can Cloudflare Workers use SMTP?

Workers cannot open outbound connections on port 25. The connect() sockets API can reach other ports such as 465 and 587, but you need an SMTP client written for Workers sockets; Nodemailer and similar Node libraries do not work. An HTTPS email API avoids the problem.

How do I store an email API key in a Worker?

Run wrangler secret put MAILCANDOR_KEY. The value is encrypted and shows up on the env object passed to your fetch handler as env.MAILCANDOR_KEY.

Does Cloudflare have its own email sending?

Yes. Cloudflare's Email Service can send through a send_email binding in Workers, a REST API or SMTP, with sending domains verified on Cloudflare. Check its current limits and pricing in Cloudflare's docs.

What is Cloudflare Email Routing?

Email Routing forwards mail that arrives at addresses on your domain to another inbox or to an Email Worker. It handles incoming mail, not sending from your app.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.