Looking to hire Laravel developers? Try LaraJobs

laravel-worker-mail-relay maintained by jhemmmm

Description
Send Laravel mail through any SMTP provider from a Cloudflare Worker.
Last update
2026/11/30 08:20 (v1.0.1)
License
Downloads
7

Comments
comments powered by Disqus

Laravel Worker Mail Relay

Send Laravel mail through any SMTP provider from a Cloudflare Worker.

Laravel app ──HTTPS + HMAC──▶ Cloudflare Worker ──SMTP over TLS──▶ your SMTP provider ──▶ recipient

The app builds the finished message as usual (Symfony Mailer) and POSTs it to a Worker you own. The Worker logs in to your provider over TLS and hands the message over with MAIL FROM / RCPT TO / DATA.

SPF, DKIM and DMARC don't change: your provider still sends and signs the message.

Quick start

composer require jhemmmm/laravel-worker-mail-relay

Add the Cloudflare token next to your usual mail login in .env:

CLOUDFLARE_API_TOKEN=...
MAIL_HOST=smtp.example.com
MAIL_PORT=465
MAIL_USERNAME=you@example.com
MAIL_PASSWORD=...

Upload the Worker and send a test message:

php artisan mail-relay:install
php artisan mail-relay:test you@example.com

Then set MAIL_MAILER=worker (MAIL_DRIVER=worker with a legacy flat config/mail.php) and reload the config.

APP_URL should be set to your real domain. It names the Worker, e.g. https://example.com gives example-com-mail-relay.

Provider examples

Use any host and any port except 25, which Workers block. Use implicit TLS (on) or STARTTLS. Plain-text SMTP is never allowed.

Provider MAIL_HOST MAIL_PORT TLS mode
Namecheap Private Email mail.privateemail.com 465 / 587 on / starttls
Gmail / Google Workspace smtp.gmail.com 465 / 587 on / starttls
Zoho Mail smtp.zoho.com (region specific) 465 / 587 on / starttls
Fastmail smtp.fastmail.com 465 on
Mailgun SMTP smtp.mailgun.org 465 / 587 / 2525 on / starttls / starttls

These rows are examples. Check your provider's docs for the current host, port and login rules.

Install

The service provider is auto-discovered. To customise the config file:

php artisan vendor:publish --tag=mail-relay-config

Requires PHP 8.4 and Laravel 12 or 13.

Configuration

Only CLOUDFLARE_API_TOKEN and the MAIL_* login are required. Everything else has a default that you can override. The SMTP settings are only read by mail-relay:install, which stores them in the Worker.

Config key Env Default Purpose
url MAIL_RELAY_URL looked up from Cloudflare The Worker URL. Only needed for a custom domain.
secret MAIL_RELAY_SECRET HMAC-SHA256 of APP_KEY (64 hex characters) Shared signing secret, at least 32 characters. Install stores it as the Worker secret RELAY_SECRET. APP_KEY can't be recovered from it.
timeout MAIL_RELAY_TIMEOUT 30 Seconds the app waits for the Worker.
worker MAIL_RELAY_WORKER slug of the APP_URL host (or APP_NAME) + -mail-relay Worker name, 1–63 characters from a-z0-9-.
cloudflare.token CLOUDFLARE_API_TOKEN – (required) API token.
cloudflare.account_id CLOUDFLARE_ACCOUNT_ID the only account the token can see Set it if the token sees several accounts.
smtp.host MAIL_HOST – (required) SMTP host. Becomes SMTP_HOST.
smtp.port MAIL_PORT 587 Any port from 1 to 65535 except 25. Becomes SMTP_PORT.
smtp.tls MAIL_RELAY_TLS on for ports 465 and 2465, otherwise starttls on means implicit TLS. starttls means the connection is upgraded first. Nothing else is accepted. Becomes SMTP_TLS. MAIL_ENCRYPTION is not used.
smtp.username MAIL_USERNAME – (required) SMTP login. Becomes a secret.
smtp.password MAIL_PASSWORD – (required) SMTP password. Becomes a secret.
smtp.ehlo MAIL_EHLO_DOMAIN the host of APP_URL Name sent in EHLO. Becomes EHLO_HOST.

If you rotate APP_KEY, run mail-relay:install again so the Worker gets the new secret.

The package also adds mail.mailers.worker (['transport' => 'worker']) if your config/mail.php doesn't define it.

Docker and the config cache

mail-relay:install never writes .env. The Worker URL is kept in the cache, so a read-only .env mount works. If the app and the install command don't share a cache, or the app has no Cloudflare token, set MAIL_RELAY_URL instead. After changing .env, clear or rebuild the config cache: run php artisan config:clear / optimize, or recreate the containers if they cache the config at start-up.

Cloudflare API token

Create a token at My Profile → API Tokens → Create Token → Custom token with:

  • Account → Workers Scripts → Edit, scoped to the account that will host the Worker.

That one permission covers the calls install makes. No zone permissions are needed.

The account id is optional. Without it, the package asks Cloudflare for the token's accounts and uses the only one it finds. If it can't find your account, set CLOUDFLARE_ACCOUNT_ID. The id is shown on the Workers & Pages overview page, and in the dashboard URL: dash.cloudflare.com/<account id>/....

The account needs a workers.dev subdomain. If you have never opened Workers & Pages in the dashboard, open it once to create one. Install stops with that hint if the subdomain is missing.

What was checked against developers.cloudflare.com (November 2026)

  • PUT /accounts/{account_id}/workers/scripts/{script_name} takes multipart/form-data.
    • The metadata part holds JSON with main_module, compatibility_date and bindings.
    • main_module names the part that holds the entry module. Each module is its own part, named after its file.
    • ES module parts use the content type application/javascript+module.
    • Accepted permissions include Workers Scripts Write (shown as "Workers Scripts: Edit" in the dashboard).
  • Bindings: {"type": "plain_text", "name": …, "text": …} and {"type": "secret_text", "name": …, "text": …}.
  • compatibility_date: if it is left out, it defaults to 2021-11-02, so install always sends one.
  • POST /accounts/{account_id}/workers/scripts/{script_name}/subdomain takes {"enabled": true}. Accepted permissions include Workers Scripts Write.
  • GET /accounts/{account_id}/workers/subdomain returns result.subdomain. Accepted permissions include Workers Scripts Write and Workers Scripts Read. Account Settings is not listed.
  • Port 25: Workers can't open outbound TCP connections on it. startTls() requires secureTransport: "starttls" and returns a new socket.

Not verified: whether a script upload without some bindings keeps them. The docs don't say, so every install sends the full set. Also not verified: the exact error code Cloudflare returns when an account has no workers.dev subdomain, and whether GET /accounts works for a token that only has Workers access.

Install, switch, test

  1. Set the .env values from the Quick start.

  2. Upload the Worker:

    php artisan mail-relay:install
    

    Run it again whenever the SMTP login, port, TLS mode, APP_KEY or secret changes, or after upgrading the package.

  3. Send a test message. This works before you switch the app's mailer:

    php artisan mail-relay:test you@example.com
    
  4. Switch the mailer, then reload the config:

    • Modern config/mail.php (with a mailers array): MAIL_MAILER=worker.
    • Legacy flat config/mail.php ('driver' => env('MAIL_DRIVER')): MAIL_DRIVER=worker.

Worker contract

The request is POST with a JSON body {"from": "a@example.com", "to": ["b@example.com", …], "raw": "<base64 of the full RFC 5322 message>"}. to holds every envelope recipient (to, cc and bcc). The message itself carries no Bcc: header.

Signature: X-Signature: {expires}.{hex hmac_sha256("{expires}.{body}", MAIL_RELAY_SECRET)}. The app sets expires to now + 300 seconds.

The Worker checks requests in this order. Nothing unsigned is parsed.

Status When
405 The method isn't POST.
413 The body is over 20 MB, by Content-Length or by actual size.
401 The signature is missing or malformed, expired, more than 600 s in the future, or wrong. It is checked with crypto.subtle.verify.
400 Bad JSON or base64, an empty message, 0 or more than 100 recipients, or an address that isn't ^[^\s<>@]+@[^\s<>@]+$ (this also blocks CR/LF injection).
502 An unexpected SMTP reply or connection error. The body is SMTP <step>: <reply>, e.g. SMTP auth: 535 5.7.8 Authentication failed.
504 No SMTP reply within 15 s (optional SMTP_TIMEOUT binding, in seconds).
200 The provider accepted the message. The body is its final 250 reply.

SMTP steps

  1. Connect with secureTransport set by SMTP_TLS, not by the port.
  2. Wait for the 220 greeting, then EHLO.
  3. With starttls: send STARTTLS and expect 220, upgrade the socket, and EHLO again. If STARTTLS isn't offered, the Worker stops with a 502 before any login is sent.
  4. Log in with AUTH PLAIN if offered, otherwise AUTH LOGIN. Expect 235.
  5. MAIL FROM, then RCPT TO for each recipient (250 or 251).
  6. DATA, then the message with CRLF line endings, dot-stuffed and ended with .. Expect 250.
  7. QUIT. The socket is always closed.

Multi-line replies (250-…) and replies split across TCP chunks are handled.

The Worker is plain ES modules with no build step and no dependencies. worker/relay.js only wires cloudflare:sockets to worker/handler.js.

Development

composer install
composer test        # PHPUnit (Orchestra Testbench) + node --test worker/

The Worker tests run against a scripted fake SMTP server and need Node 20 or newer.

Limitations

  • Logins come from changing Cloudflare addresses. Some providers limit or block logins from unfamiliar networks, or require an app password (Gmail, for example).
  • Workers Free plan limits apply, such as 100,000 requests a day. Time spent waiting on the socket doesn't count as CPU time. Very large messages may still hit the CPU limit on the Free plan.
  • If PHP times out (MAIL_RELAY_TIMEOUT) while the Worker is still talking to the provider, a retry can send a duplicate.
  • A signed request can be replayed until it expires (5 minutes). Capturing one requires breaking HTTPS.
  • There is no SMTPUTF8, so mailbox names must be ASCII. Domains are sent IDN-encoded.
  • One Worker holds one SMTP login. Use one Worker per app or mailbox.
  • Default names can collide. Two apps with APP_URL=http://localhost get the same Worker name, so set MAIL_RELAY_WORKER for one of them.

License

MIT