Skip to content

About

A robust, modular Node.js SMTP relay server designed to receive standard SMTP connections and forward emails seamlessly via the Cloudflare REST API.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Cloudflare SMTP Relay

Latest Release License: Apache 2.0 CI/CD Docker Image Node.js Ask DeepWiki Security Policy

A robust, modular Node.js SMTP relay server designed to receive standard SMTP connections and forward emails seamlessly via the Cloudflare REST API.


Do You Need This Relay?

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 STARTTLS it advertises uses a self-signed certificate built into the smtp-server library, 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.


Features

  • Cloudflare API Integration: Forwards emails reliably using Cloudflare's Email Sending API (/email/sending/send).
  • Attachment Support: Full MIME parsing via mailparser with 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.

How It Works

+----------------+      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

Prerequisites

  • 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.

Installation & Quickstart

  1. Clone the repository:

    git clone https://github.com/divmora/cloudflare-smtp-relay.git
    cd cloudflare-smtp-relay
  2. Install dependencies:

    pnpm install
  3. Set up configuration:

    cp config.example.yml config.yml
  4. Edit config.yml: Fill in your Cloudflare credentials (cloudflare_account_id and cloudflare_api_token) and define your SMTP users and security policies.

Note: config.yml and .env are automatically ignored by Git to keep your credentials secure.


Configuration Reference

The relay server is configured via a YAML file (config.yml by default, or the path set in SMTP_RELAY_CONFIG_PATH).

Configuration Options

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

Access Control & Validation Rules

  • Precedence: If a user specifies user-level allowed_* lists in smtp_users, those lists are evaluated for that user. If empty, the relay falls back to the corresponding global.allowed_* lists.
  • Rule Matching: If both allowed_*_emails and allowed_*_domains are 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 FROM and each envelope recipient at RCPT TO, so disallowed addresses are refused before the message is sent. Header To/Cc/Bcc addresses 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 5xx reply so clients stop retrying. Timeouts, network errors, Cloudflare 401/403 (invalid, expired or under-scoped token), 429 and 5xx responses return 451 so clients keep the message and retry later. Oversized messages get 552.

Recipients

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_bytes and max_clients are read at startup; changing them needs a restart. Other options are picked up by the hot reload.


Environment Variables

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

Deployment & Usage

1. Running Locally

Start the SMTP relay server:

pnpm start

The server will bind to the configured smtp_host and smtp_port (default 127.0.0.1:587 or 0.0.0.0:587).


2. Running with Docker Compose

  1. Make sure config.yml is populated in the root directory.
  2. Start the container:
    docker-compose up -d --build
  3. View logs:
    docker-compose logs -f

3. Running with Pre-built Docker Image (GHCR)

Published Docker images are available from GitHub Container Registry:

  • Production Releases (Tags): ghcr.io/divmora/cloudflare-smtp-relay:latest or ghcr.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:latest

4. Deploying to Kubernetes

Kubernetes manifests are provided in the k8s/ folder:

  1. Update k8s/secret.yaml with 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.
  2. Apply the manifests:
    kubectl apply -f k8s/secret.yaml
    kubectl apply -f k8s/deployment.yaml
    kubectl apply -f k8s/service.yaml
    The Service is ClusterIP, so the relay is only reachable inside the cluster (cloudflare-smtp-relay:587). Keep it that way until inbound TLS is supported.
  3. Verify the deployment:
    kubectl get pods -l app=cloudflare-smtp-relay
    kubectl get svc cloudflare-smtp-relay

Running as Non-Root

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 (as docker-compose.yml does). Docker's default bridge network allows non-root processes to bind port 587. With network_mode: host it does not, so use smtp_port: 2525 (or any port >= 1024) there.
  • Kubernetes: set runAsUser: 1000 and the pod sysctl net.ipv4.ip_unprivileged_port_start: "0" (as k8s/deployment.yaml does). 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: 1000 takes 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 from 1.1.x

Upgrading only the image keeps existing deployments working. These behaviour changes apply:

  • Message size limit: messages over 25 MiB are rejected with 552. Set max_message_size_bytes: 0 for no limit.
  • Recipients: mail goes only to SMTP envelope recipients (RCPT TO). Addresses that appear only in the To/Cc headers are no longer mailed.
  • Reply codes: blocked senders and recipients get a permanent 550 instead of a temporary 450, so clients stop retrying.
  • Allowlists match case-insensitively.
  • Environment variables: CLOUDFLARE_API_TOKEN and CLOUDFLARE_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.yaml is replaced by k8s/secret.yaml, and the Service is ClusterIP instead of LoadBalancer. Existing clusters keep their current objects until you apply the new files.

Health Checks

A dedicated HTTP server (default port 8080) exposes:

  • GET /healthz – liveness: returns 200 while the process is running.
  • GET /readyz – readiness: returns 200 when 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 by cloudflare_health_check_interval_ms), otherwise 503 with a JSON breakdown.

Testing

Automated Unit Tests

Run the automated test suite powered by Node.js native test runner:

pnpm test

End-to-End Test Client

A 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.js

Build & Development Automation

A 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

Project Structure

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

Community & Contributing

  • 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.

License

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.

About

A robust, modular Node.js SMTP relay server designed to receive standard SMTP connections and forward emails seamlessly via the Cloudflare REST API.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages