Sending email from a Cloudflare Worker, over plain SMTP
2026-11-02
Workers can't use port 25, but they can open TLS sockets. A small SMTP client was all it took to send the site's mail through my own server.
The contact form on this site emails me the brief. I didn't want a mail API in the middle, since I already run a mail server. The catch: Cloudflare blocks port 25 from Workers, so plain relaying is out.
Sockets are enough
Workers can open TCP sockets with cloudflare:sockets. Port 465 is TLS from the first byte; port 587 starts plain and upgrades with STARTTLS. Either way it's a login on my own server, which is allowed.
connect({ hostname, port }, { secureTransport: port === 465 ? "on" : "starttls" })The details that matter
- From is the account I log in as, so the server signs the message for my domain and it doesn't land in spam.
- Reply-To is the client, so answering the email answers them.
- Header words are RFC 2047 encoded. Besides handling any language, it means a name with a line break in it can't sneak in an extra header.
- Bodies are base64, so no line is ever too long, and any line starting with a dot gets a second one, or the server would think the message ended early.
The whole client is under 150 lines with no dependencies, and the password is a Worker secret.