tutorials
SMTP relay from Cloudflare Workers: the 2026 capability boundary
November 16, 2026

You moved a service to a Cloudflare Worker, kept your trusty nodemailer relay code, deployed, and every send hangs and then throws. The code is fine. The runtime cannot do what the code is asking.
SMTP is the oldest reliable thing in the email stack. You have a relay host, a port, a username and password, and a library that speaks the protocol. It has worked on every server you have ever run. Then you move the same code onto a Cloudflare Worker and it stops cold, with errors that look like networking flakiness but never resolve on retry.
This is usually a runtime/library mismatch or a prohibited destination, not a
universal ban on TCP. Workers expose outbound connect() sockets, including TLS and
STARTTLS. The hard boundaries are outbound port 25 and TCP destinations in
Cloudflare-owned IP ranges. This post explains those boundaries and the HTTPS path
that remains the simplest production choice.
Why does SMTP relay fail from a Cloudflare Worker?
A Cloudflare Worker has outbound TCP, but three distinctions decide whether SMTP is viable:
- Port 25 is prohibited. A Worker cannot perform direct-to-MX delivery.
- Cloudflare IP ranges are prohibited TCP destinations. That makes
smtp.mx.cloudflare.net:465unavailable from a Worker even though external apps can use it. - Node SMTP libraries are not the socket API contract. A third-party relay on
465/587 may be reachable with a purpose-built
connect()client, but nodemailer compatibility must be verified rather than assumed.
Here is the kind of code people bring over from a Node server. It is correct SMTP code. It just cannot run here:
// nodemailer-style relay. This does NOT work on a Worker.
import nodemailer from "nodemailer";
export default {
async fetch(): Promise<Response> {
const transport = nodemailer.createTransport({
host: "smtp.provider.com",
port: 587,
auth: { user: "apikey", pass: "secret" },
});
await transport.sendMail({
from: "hello@yourdomain.com",
to: "user@example.com",
subject: "Hello",
text: "Test",
});
return new Response("sent");
},
};
What you actually see at build or runtime is one of these, depending on bundler and version:
Error: No such module "node:net".
Error: proxy request failed, cannot connect to the specified address
The first is a Node compatibility problem. The second is what a prohibited target, such as a Cloudflare-owned IP, can produce. For Cloudflare Email Service, the supported Worker transports are the binding and REST API; authenticated SMTP on 465 is the external-client compatibility path.
If that feels like an arbitrary limitation, it is the same reason MailChannels existed as a free Workers relay for years, and the same reason every edge sender is HTTPS-based. We cover that history in the MailChannels deprecation post.
How do I relay through an SMTP provider over HTTPS instead?
Use your provider's HTTPS send endpoint rather than its SMTP host. Almost every "SMTP provider" is really a relay company that exposes two front doors to the same delivery engine: a classic SMTP host you point a mail library at, and an HTTPS API that takes the same message. The SMTP-to-the-recipient hop happens on their infrastructure either way. From a Worker you simply use the HTTPS door.
The mental model matters: you are still relaying over SMTP, you are just not the one opening the SMTP socket. Your Worker POSTs the message to the provider over HTTPS, and the provider performs the real SMTP delivery to the recipient's MX server from an IP that is allowed to.
Here is the pattern with Mailgun, whose HTTPS endpoint takes form-encoded fields:
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const form = new FormData();
form.set("from", "Your App <hello@yourdomain.com>");
form.set("to", "user@example.com");
form.set("subject", "Reset your password");
form.set("html", "<p>Click to reset.</p>");
const res = await fetch(
`https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`,
{
method: "POST",
headers: {
// Basic auth: "api" as username, your key as password.
authorization: `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}`,
},
body: form,
},
);
if (!res.ok) return new Response(await res.text(), { status: 502 });
return new Response("relayed");
},
};
SMTP2GO, SendGrid, Postmark, and Brevo are the same shape with a different URL and auth header. The point is not which one you pick; it is that the request is an HTTPS fetch, which the runtime can do, instead of a socket, which it cannot. For the wider set of edge-friendly send paths and how they compare, see the ways to send email from Cloudflare Workers.
Store the credentials as Worker secrets so they are not in your repo:
npx wrangler secret put MAILGUN_API_KEY
npx wrangler secret put MAILGUN_DOMAIN
The first failure you will hit: unverified domain
Before DNS is in place, the relay rejects you even with a valid key. Expect something like:
{
"message": "Domain yourdomain.com is not yet verified. Check DNS records."
}
This is authentication, not authorization. A relay will accept your API key but refuse to send as a domain you have not proven you control. The fix is the DNS records the provider hands you: an SPF include so receivers accept their IPs on your behalf, a DKIM key so messages are signed, and a DMARC policy:
TXT @ v=spf1 include:mailgun.org ~all
TXT smtp._domainkey k=rsa; p=MIIBIjANBg...
TXT _dmarc v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com
Once those resolve, the same POST returns a 200 and a queued message id. If you want to understand each record rather than paste it, the SPF, DKIM, and DMARC walkthrough covers them end to end, and the deliverability guide covers what happens after a record passes.
What if I really need to speak SMTP, not HTTP?
If a downstream system or library can only emit SMTP, run an SMTP-to-HTTPS gateway outside the Worker and have it call Tinbox. This preserves Tinbox's authorization, suppression, and idempotency ledger while giving the legacy client an SMTP surface. You have two honest choices:
- Use the provider's HTTPS API and drop the SMTP requirement. This is the right answer in almost every case. The "SMTP" requirement is usually a habit, not a hard constraint, because the same provider relays the message over SMTP regardless of which door you used.
- Put a tiny relay process somewhere with sockets. A small container or VM (Cloudflare Containers, a cheap box, a Fly machine) can run nodemailer against your SMTP host, and your Worker calls it over HTTPS. You have now reintroduced a server to maintain, which is usually the thing you were trying to avoid by going edge-first, so weigh it carefully.
The thing you cannot do, no matter how you arrange it, is the final SMTP-to-MX hop from inside the Worker itself. That hop always lives on infrastructure with port-25 access. The only design decision is whose infrastructure: a relay provider's, a box you run, or your own Cloudflare account fronted by HTTPS, which is the next section.
How do I run my own SMTP relay on my own Cloudflare account?
Front the relay with HTTPS inside your own account: a Worker enqueues the message, a consumer signs and delivers it, and bounces flow back to your database, so no third-party relay sits in the path. You cannot escape the port-25 reality, but you can decide that the relay infrastructure belongs to you instead of to Mailgun or SendGrid.
Built from scratch, this is a real project. You need a producer Worker that accepts a send and enqueues it, a Cloudflare Queue so one request does not block on delivery, a consumer that signs the message with DKIM and performs delivery over a path that is permitted to reach MX servers, bounce and complaint parsing, and a suppression list so you stop mailing dead addresses. None of it is exotic, but it is weeks of work plus ongoing care, which is exactly why relay providers exist. If you want to see the queue half of it built out, the Queues sending tutorial walks that piece, and the Cloudflare Queues patterns for reliable email sending catalogs the retry, batching, and rate-limit shapes you will reach for.
Or you deploy a relay that is already built onto your own account. That is what Tinbox is. One command provisions the resources and prints the DNS you need:
npx tinbox init yourdomain.com
Provisioned D1 database (tinbox-yourdomain-db)
Provisioned R2 bucket (tinbox-yourdomain-mail)
Provisioned Queue (tinbox-yourdomain-send)
Add these DNS records to yourdomain.com:
TXT @ v=spf1 include:_spf.yourdomain.com ~all
TXT tinbox._domainkey v=DKIM1; k=rsa; p=MIIBIjANBg...
TXT _dmarc v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com
Once DNS propagates, run: npx tinbox doctor
The send from your Worker becomes a binding call rather than a fetch to someone else's domain:
import { tinbox } from "tinbox/cf";
export default {
async fetch(req: Request, env: Env): Promise<Response> {
await tinbox(env).send({
to: "user@example.com",
from: "hello@yourdomain.com",
subject: "Reset your password",
html: `<p>Click <a href="https://app.yourdomain.com/reset?t=abc">here</a> to reset.</p>`,
});
return new Response("relayed");
},
};
tinbox(env).send(...) enqueues onto a Cloudflare Queue in your account and returns immediately, so the request stays fast. A consumer Worker signs the message with DKIM and performs delivery, handles retries and bounces, and writes results back to your own D1 database. The SMTP-to-MX hop still happens on infrastructure that can reach port 25, the same as with any relay, but the queue, the DKIM keys, the bounce data, and the suppression list are yours, and there is no per-email invoice from a third party in the path.
Be precise about the tradeoff so you choose with eyes open. With this path you own your sending reputation and your DNS, exactly as you would with a paid relay account, and you do warmup yourself. What you get back is that nothing in your relay pipeline lives on a vendor that can change terms or deprecate a route. If you are weighing this against a hosted relay on price, the cost breakdown has the curves.
Common failure modes when relaying from a Worker
The errors you will actually see, and what each one means:
No such module "node:net" / "node:tls"
Your bundle still references a Node SMTP library. Remove nodemailer from the Worker,
then use an HTTPS API or binding. A Worker-native SMTP client is a separate option
only when its third-party submission destination is allowed and the client has been
tested against the Workers connect() API.
proxy request failed, cannot connect to the specified address
The destination is prohibited. Cloudflare IP ranges, localhost, and private IPs are
blocked TCP targets. If this is smtp.mx.cloudflare.net, switch to the Email Service
binding or REST API.
401 Unauthorized from the relay endpoint
Wrong or missing API key. Confirm the secret was pushed with wrangler secret put, not just set in your local .dev.vars, and that the auth header format matches the provider (Basic vs Bearer).
Domain not verified / 550 sender rejected
Your from domain is not authenticated with the relay. Add the SPF include, DKIM key, and DMARC record the provider gave you and wait for propagation before retrying.
Works in dev, fails when deployed
A secret or binding did not make it to production. Local wrangler dev reads .dev.vars; the deployed Worker needs wrangler secret put for keys and the queue binding declared in wrangler.jsonc for a self-hosted relay.
The short version
Workers do have outbound TCP, but port 25 and Cloudflare-owned IP ranges are blocked. That prevents direct-to-MX delivery and prevents Worker TCP access to Cloudflare's own SMTP endpoint. A third-party submission relay on 465/587 may be technically reachable with a Worker-native client, but the production default remains a binding or HTTPS API. External SMTP-only applications can use Cloudflare's authenticated submission endpoint directly, or use a Tinbox SMTP gateway when ledgered authorization matters.
Deploy this yourself: npx tinbox init yourdomain.com, and see the docs for the full relay, DNS, and bounce-handling setup.
Frequently asked questions
Can a Cloudflare Worker connect to an SMTP server over port 25 or 587?
Port 25 is prohibited. Ports 465 and 587 are not documented as blanket-blocked, and connect() supports TLS/STARTTLS, so a purpose-built client may reach a third-party relay. Workers cannot reach Cloudflare's own SMTP endpoint because outbound TCP to Cloudflare IP ranges is blocked.
How do I relay outbound email through an SMTP provider from a Worker then?
Use the provider's HTTPS send API instead of its SMTP endpoint. Most SMTP relay providers (Mailgun, SMTP2GO, SendGrid, Postmark, Brevo) expose an HTTPS endpoint that accepts the same message and performs the SMTP delivery on their infrastructure. Your Worker makes an authenticated HTTPS POST, and the provider relays it to the recipient's MX server over real SMTP.
Why does nodemailer not work on Cloudflare Workers?
nodemailer assumes Node's net, tls, dns, and connection lifecycle. Workers expose a different connect() API, so compatibility depends on the runtime and bundle rather than SMTP being categorically absent. Use a binding or HTTPS API unless you maintain and test a Worker-native SMTP client.
Is calling an HTTPS API still an SMTP relay?
Functionally yes. Your Worker hands the message to a provider over HTTPS, and the provider relays it to the destination over SMTP. The SMTP conversation still happens, just on infrastructure that is allowed to open port 25. The only thing that changes is the first hop from your Worker, which is HTTPS instead of a raw SMTP socket.
Can I run my own SMTP relay on Cloudflare instead of using a provider?
You cannot run the final SMTP-to-MX hop from a Worker because of the port-25 block, but you can own the entire relay pipeline on your Cloudflare account by fronting it with HTTPS: a Worker enqueues the message, a consumer signs it with DKIM and performs delivery, and bounces and suppression are written back to your D1. Tinbox packages exactly this so you are not tied to a third-party relay.