A blazing fast, modular, zero-dependency SMTP API built exclusively for Cloudflare Workers.
This project demonstrates how to send transactional emails natively from the edge by communicating directly with Google's SMTP servers (smtp.gmail.com) over raw TCP using the new cloudflare:sockets API.
- Zero Dependencies: Absolutely no
nodemailer,worker-mailer, or heavy npm packages. - Native Sockets: Uses Cloudflare's
connect()to establish a raw TCP socket connection to Google. - Secure STARTTLS: Dynamically upgrades the plaintext socket to an encrypted TLS connection mid-stream (
socket.startTls()), fully complying with RFC 3207. - Production-Ready Structure: Clean, modular, and maintainable TypeScript architecture.
- Edge Optimized: Instant execution time with practically zero cold-start bloat.
mailservicing/
├── src/
│ ├── index.ts # The Cloudflare Worker entry point (Routing, CORS, Input validation)
│ ├── mailer.ts # Service to negotiate the SMTP handshake and format the MIME message
│ ├── smtp-client.ts # The underlying Raw TCP/TLS socket reader/writer wrapper class
│ └── types.ts # Typescript interfaces
├── .dev.vars # (Ignored) Local secrets
└── wrangler.toml # Cloudflare Worker configuration
Since standard Gmail passwords cannot be used for direct SMTP authentication:
- Go to your Google Account > Security.
- Ensure 2-Step Verification is turned ON.
- Search for App passwords and create one named "Cloudflare Worker".
- Copy the 16-character password.
Clone the repository, navigate to the folder, and install the TypeScript definitions and Wrangler CLI.
npm installCreate a .dev.vars file in the root directory for your local secrets:
GMAIL_USER=[email protected]
GMAIL_APP_PASSWORD=your-16-character-passwordSpin up the Wrangler development server:
npm run devTest your local endpoint using curl:
curl -X POST http://localhost:8787 \
-H "Content-Type: application/json" \
-d '{"to":"[email protected]", "subject":"Testing my custom SMTP", "text":"Look mom, zero dependencies!"}'Deploying to Cloudflare's global edge network takes seconds.
1. Deploy the code:
npx wrangler deploy2. Add your secrets to Cloudflare: You must upload your Google credentials to Cloudflare's secure vault so your production worker can access them.
npx wrangler secret put GMAIL_USER
npx wrangler secret put GMAIL_APP_PASSWORD3. Test Production:
Replace localhost:8787 with your newly deployed *.workers.dev URL and fire your request!
If you look inside src/mailer.ts, you'll see the exact sequence of commands we send over the TCP socket:
connect()tosmtp.gmail.com:587(Plaintext)- Send
EHLO - Send
STARTTLS - Upgrade socket to TLS via
socket.startTls() - Send
EHLO(Encrypted) - Send
AUTH PLAIN(Base64 encoded) - Send
MAIL FROMandRCPT TO - Send
DATAfollowed by the raw email headers and body - Send
QUIT
All natively on the edge!