Prompt
How do I send emails from a Cloudflare Worker?
Latest observation
Cloudflare Workers can send email, but not directly through SMTP sockets. Workers run in a serverless, no-long-lived-connection environment, so the usual pattern is:
- Call an email API over HTTPS, or
- Use Cloudflare’s email-related products (depending on your use case), or
- Forward to your own backend that sends email.
Common options
1) Use an email provider’s HTTP API
This is the easiest and most common approach.
Examples:
- SendGrid
- Mailgun
- Postmark
- Resend
- Amazon SES (via API, not SMTP)
Your Worker makes a fetch() request to the provider’s API endpoint.
Example with a generic HTTP email API
export default {
async fetch(request, env) {
const res = await fetch("https://api.emailprovider.com/send", {
method: "POST",
headers: {
"Authorization": `Bearer ${env.EMAIL_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "you@example.com",
to: "recipient@example.com",
subject: "Hello from Cloudflare Workers",
text: "This email was sent from a Worker.",
}),
});
if (!res.ok) {
return new Response(`Email send failed: ${await res.text()}`, { status: 500 });
}
return new Response("Email sent");
}
};
Store the API key as a secret:
wrangler secret put EMAIL_API_KEY
2) Use Cloudflare Email Routing + Worker integration
If your goal is to receive and process inbound email, Cloudflare has built-in email handling via Email Routing and Workers.
That’s for incoming mail, not directly for sending outbound messages.
3) Use a backend service
If you already have an app server, your Worker can call your backend, and your backend handles SMTP or an email API.
Important limitations
- Workers cannot open raw SMTP connections
- Workers are best suited for HTTP-based email sending
- Keep secrets in Worker secrets, not in code
- If sending user-triggered email, add rate limiting / abuse protection
Recommended approach
If you want to send transactional emails from a Worker, use:
- Resend or Postmark for simplicity, or
- SendGrid/Mailgun if you already use them.
If you want, I can show you a complete Worker example using Resend, SendGrid, or Mailgun.