A robust, modular Node.js SMTP relay server designed to receive standard SMTP connections and forward emails seamlessly via the Cloudflare REST API.
Cloudflare Email Service now offers its own authenticated SMTP submission (beta): smtp.mx.cloudflare.net, port 465, implicit TLS, with a Cloudflare API token as the password. If your application can use that, connect it to Cloudflare directly.
This relay is still useful when:
- The client can't use port 465 with implicit TLS, for example printers, appliances and older software that only speak plain SMTP or STARTTLS on port 587.
- You don't want every application to hold a Cloudflare API token. Each app gets its own SMTP username and password; the single token stays on the relay.
- You want per-app sender and recipient allowlists (
allowed_from_*,allowed_to_*).
Security: the relay has no TLS certificate configuration yet. It accepts SMTP passwords without TLS, and the
STARTTLSit advertises uses a self-signed certificate built into thesmtp-serverlibrary, whose key is public. Treat traffic as unencrypted: run the relay only on a trusted network (same host, private Docker network or inside a Kubernetes cluster), never on a public interface.
- Cloudflare API Integration: Forwards emails reliably using Cloudflare's Email Sending API (
/email/sending/send). - Attachment Support: Full MIME parsing via
mailparserwith automatic base64 encoding for email attachments. - Dynamic Configuration: YAML-based configuration (
config.yml) with configurable in-memory hot-reloading (config_refresh_interval_ms) without server restarts. - Granular Security & Authorization: Multi-user authentication with domain-level and email-level restriction controls for both incoming and outgoing addresses.
- Container & Kubernetes Ready: Dockerfile, Docker Compose, and complete Kubernetes deployment manifests (
k8s/) included. - Automated Test Suite: Built-in unit tests using Node.js native test runner and an interactive end-to-end Nodemailer client.
+----------------+ SMTP (587) +-------------------------+
| Application | --------------------> | Cloudflare SMTP Relay |
| (or Mail User) | | (Node.js) |
+----------------+ +-------------------------+
|
1. Authenticate user
2. Parse MIME & attachments
3. Validate Sender/Recipient rules
|
HTTPS REST API (POST)
Bearer API Token
v
+-------------------------+
| Cloudflare API |
| (/email/sending/send) |
+-------------------------+
|
v
Delivered to Recipient
- Node.js 22, 24, or 26 only
- pnpm (Package manager, version 9 or 10)
- Docker & Docker Compose (Optional, for containerized deployments)
- Cloudflare Account with an active Account ID and an API Token having Email Sending permissions for your verified domains.
-
Clone the repository:
git clone https://github.com/divmora/cloudflare-smtp-relay.git cd cloudflare-smtp-relay -
Install dependencies:
pnpm install
-
Set up configuration:
cp config.example.yml config.yml
-
Edit
config.yml: Fill in your Cloudflare credentials (cloudflare_account_idandcloudflare_api_token) and define your SMTP users and security policies.
Note:
config.ymland.envare automatically ignored by Git to keep your credentials secure.
The relay server is configured via a YAML file (config.yml by default, or the path set in SMTP_RELAY_CONFIG_PATH).
global:
smtp_host: "0.0.0.0" # Host interface to bind to (e.g. 127.0.0.1 or 0.0.0.0)
smtp_port: 587 # SMTP port to listen on
health_host: "0.0.0.0" # Healthcheck bind host (defaults to smtp_host)
health_port: 8080 # Healthcheck HTTP port (default 8080, 0 disables)
cloudflare_health_check_interval_ms: 60000 # How often to verify the Cloudflare token for /readyz (0 disables)
config_refresh_interval_ms: 300000 # Interval (in ms) to reload config file (0 or omitted = disabled)
cloudflare_request_timeout_ms: 30000 # Timeout for each Cloudflare send request (default 30000)
max_message_size_bytes: 26214400 # Largest accepted message in bytes (default 25 MiB, 0 disables)
max_clients: 0 # Max concurrent SMTP connections (default 0 = no limit)
cloudflare_account_id: "YOUR_ACCOUNT_ID" # Cloudflare Account ID
cloudflare_api_token: "YOUR_API_TOKEN" # Cloudflare API Bearer Token (or CLOUDFLARE_API_TOKEN env var)
allowed_from_emails: [] # Default allowed sender emails (empty = no restriction)
allowed_to_emails: [] # Default allowed recipient emails (empty = no restriction)
allowed_from_domains: [] # Default allowed sender domains (e.g. "example.com")
allowed_to_domains: [] # Default allowed recipient domains (e.g. "mycompany.org")
smtp_users:
- username: "example_user" # SMTP authentication username
password: "example_password" # SMTP authentication password
allowed_from_emails: [] # User-level allowed sender emails override
allowed_to_emails: [] # User-level allowed recipient emails override
allowed_from_domains: [] # User-level allowed sender domains override
allowed_to_domains: [] # User-level allowed recipient domains override- Precedence: If a user specifies user-level
allowed_*lists insmtp_users, those lists are evaluated for that user. If empty, the relay falls back to the correspondingglobal.allowed_*lists. - Rule Matching: If both
allowed_*_emailsandallowed_*_domainsare empty, any address is permitted. If entries are present, an address is allowed if it matches any allowed email address OR its domain matches any allowed domain. Matching is case-insensitive. - When checks run: The envelope sender is checked at
MAIL FROMand each envelope recipient atRCPT TO, so disallowed addresses are refused before the message is sent. HeaderTo/Cc/Bccaddresses are checked again once the message is received. - Reply codes: Policy rejections and permanent Cloudflare errors (4xx other than 401, 403 and 429) return a
5xxreply so clients stop retrying. Timeouts, network errors, Cloudflare401/403(invalid, expired or under-scoped token),429and5xxresponses return451so clients keep the message and retry later. Oversized messages get552.
The message is delivered only to the SMTP envelope recipients (RCPT TO), as SMTP requires. Header To and Cc decide how each envelope recipient appears; envelope recipients not named in those headers are sent as Bcc. Addresses that appear in the headers but not in the envelope are not mailed.
max_message_size_bytesandmax_clientsare read at startup; changing them needs a restart. Other options are picked up by the hot reload.
| Variable | Description | Default |
|---|---|---|
SMTP_RELAY_CONFIG_PATH |
Path to the YAML configuration file | ./config.yml |
CLOUDFLARE_API_TOKEN |
Cloudflare API token; overrides cloudflare_api_token in the config file |
– |
CLOUDFLARE_ACCOUNT_ID |
Cloudflare Account ID; overrides cloudflare_account_id in the config file |
– |
PORT / SMTP_PORT |
(Optional) Port override for test client scripts | 587 |
Start the SMTP relay server:
pnpm startThe server will bind to the configured smtp_host and smtp_port (default 127.0.0.1:587 or 0.0.0.0:587).
- Make sure
config.ymlis populated in the root directory. - Start the container:
docker-compose up -d --build
- View logs:
docker-compose logs -f
Published Docker images are available from GitHub Container Registry:
- Production Releases (Tags):
ghcr.io/divmora/cloudflare-smtp-relay:latestorghcr.io/divmora/cloudflare-smtp-relay:<tag> - Main Branch (Debug / Development):
ghcr.io/divmora/cloudflare-smtp-relay/debug:latest
docker run -d \
--name cloudflare-smtp-relay \
-p 127.0.0.1:587:587 \
-v $(pwd)/config.yml:/app/config.yml:ro \
-e SMTP_RELAY_CONFIG_PATH=/app/config.yml \
ghcr.io/divmora/cloudflare-smtp-relay:latestKubernetes manifests are provided in the k8s/ folder:
- Update
k8s/secret.yamlwith your Cloudflare Account ID, API token and SMTP users. Both the config (which holds SMTP passwords) and the token are stored as Secrets. For production, create them with your secret manager instead of committing the file. - Apply the manifests:
The Service is
kubectl apply -f k8s/secret.yaml kubectl apply -f k8s/deployment.yaml kubectl apply -f k8s/service.yaml
ClusterIP, so the relay is only reachable inside the cluster (cloudflare-smtp-relay:587). Keep it that way until inbound TLS is supported. - Verify the deployment:
kubectl get pods -l app=cloudflare-smtp-relay kubectl get svc cloudflare-smtp-relay
The image runs as root by default so it can bind port 587 on any container runtime. To run it as the unprivileged node user (uid 1000):
- Docker / Compose: set
user: node(asdocker-compose.ymldoes). Docker's default bridge network allows non-root processes to bind port 587. Withnetwork_mode: hostit does not, so usesmtp_port: 2525(or any port >= 1024) there. - Kubernetes: set
runAsUser: 1000and the pod sysctlnet.ipv4.ip_unprivileged_port_start: "0"(ask8s/deployment.yamldoes). The sysctl is allowed by default since Kubernetes 1.22. containerd 2.x allows low ports without it, containerd 1.x does not. - Config file: must be readable by uid 1000. With Kubernetes Secrets,
fsGroup: 1000takes care of this.
If the relay cannot bind its ports or read its config file, it logs the reason and exits with code 1, so Docker or Kubernetes restarts it and the failure shows up.
Upgrading only the image keeps existing deployments working. These behaviour changes apply:
- Message size limit: messages over 25 MiB are rejected with
552. Setmax_message_size_bytes: 0for no limit. - Recipients: mail goes only to SMTP envelope recipients (
RCPT TO). Addresses that appear only in theTo/Ccheaders are no longer mailed. - Reply codes: blocked senders and recipients get a permanent
550instead of a temporary450, so clients stop retrying. - Allowlists match case-insensitively.
- Environment variables:
CLOUDFLARE_API_TOKENandCLOUDFLARE_ACCOUNT_ID, if set, override the config file. - Startup failures: an unreadable config file or a port that cannot be bound now stops the process (exit code 1) instead of leaving it running without serving mail.
- Kubernetes manifests:
k8s/configmap.yamlis replaced byk8s/secret.yaml, and the Service isClusterIPinstead ofLoadBalancer. Existing clusters keep their current objects until you apply the new files.
A dedicated HTTP server (default port 8080) exposes:
GET /healthz– liveness: returns200while the process is running.GET /readyz– readiness: returns200when the SMTP listener is bound, Cloudflare credentials are configured, and the most recent periodic Cloudflare token verification succeeded (cached; probes never call Cloudflare directly, interval set bycloudflare_health_check_interval_ms), otherwise503with a JSON breakdown.
Run the automated test suite powered by Node.js native test runner:
pnpm testA built-in test client (test-client.js) uses nodemailer to send a sample email with an attachment through the running relay server:
# Set credentials matching your config.yml (if different from defaults)
SMTP_PORT=587 SMTP_USERNAME=example_user SMTP_PASSWORD=example_password SENDER_EMAIL=sender@example.com RECIPIENT_EMAIL=recipient@example.com node test-client.jsA standardized Makefile is provided to streamline common development tasks:
| Command | Description |
|---|---|
make dev-setup |
Install project dependencies (pnpm install) |
make test |
Run the automated unit test suite (pnpm test) |
make test-client |
Run the end-to-end Nodemailer verification client |
make lint |
Run syntax validation across all JavaScript files |
make fmt |
Check code formatting |
make docker-build |
Build local Docker container image |
make clean |
Clean up temporary files, caches, and test artifacts |
cloudflare-smtp-relay/
├── .github/
│ └── workflows/
│ ├── ci.yml # Automated CI tests across Node versions (22, 24, 26)
│ ├── docker-publish.yml # Docker image build & publish to GHCR
│ ├── release-please.yml # Release Please automation via reusable workflow
│ └── semantic-pull-request.yml # Semantic PR title linter
├── k8s/ # Kubernetes deployment, service, and secrets
│ ├── deployment.yaml
│ ├── secret.yaml
│ └── service.yaml
├── src/
│ ├── cloudflare.js # Cloudflare Sending API client
│ ├── cloudflareHealth.js # Periodic Cloudflare token check for /readyz
│ ├── config.js # Configuration loader & hot-reload manager
│ ├── healthServer.js # /healthz and /readyz HTTP endpoints
│ └── smtpServer.js # SMTPServer lifecycle, auth, and validation logic
├── test/ # Unit and end-to-end test suites (node --test)
│ ├── cloudflare.test.js
│ ├── cloudflareHealth.test.js
│ ├── config.test.js
│ ├── healthServer.test.js
│ ├── relay.e2e.test.js
│ └── smtpServer.test.js
├── .gitignore # Standard git ignore rules
├── .release-please-config.json # Release Please configuration
├── .release-please-manifest.json # Version baseline tracker
├── AGENTS.md # Instructions and architecture overview for AI agents
├── CONTRIBUTING.md # Guidelines for contributing & Conventional Commits
├── Dockerfile # Container image specification
├── LICENSE # Apache License 2.0
├── Makefile # Standardized build automation targets
├── README.md # Project documentation
├── ROADMAP.md # Living product roadmap (upcoming features & debt)
├── SECURITY.md # Security policy and vulnerability disclosure
├── config.example.yml # Sample configuration template
├── docker-compose.yml # Local container orchestration
├── index.js # Application entry point
├── package.json
└── test-client.js # End-to-end SMTP client verification script
- Product Roadmap: The relay is in maintenance mode; the few planned items are in ROADMAP.md.
- AI Agents & Contributors: Read AGENTS.md for code conventions, architecture maps, and guidelines.
- Contributions: Read CONTRIBUTING.md to get started with pull requests and issues.
- Code of Conduct: Please review our Code of Conduct (inherited from
.github). - Security: To report vulnerabilities, refer to SECURITY.md.
This project is open-source software licensed under the Apache License, Version 2.0.
- Free & Unrestricted Use: Permitted for free use, reproduction, modification, distribution, and execution in any environment (including commercial, enterprise production, SaaS, private, and homelab environments) without requiring any commercial license (EULA) or payment.
- Patent Grant & Protection: Includes standard Apache 2.0 perpetual patent license grants and liability disclaimers.
See LICENSE for the full license text.