← All tutorials

Infrastructure · Email

Build a self-hosted email platform

Set up a custom-domain mailbox with Postfix, Dovecot, and Roundcube. Follow the complete build from DNS and SMTP through webmail, spam filtering, encrypted backups, and disaster recovery.

On this page 26 sections

1. What you will build

The goal was to use a personal domain as a real email service without paying for a separate mailbox hosting subscription. The service had to receive and store mail on the existing Oracle VM, send email as the custom domain, provide a web interface and standard mail-client access, and retain an additional incoming copy in Gmail. The VM was already hosting a SvelteKit application through Caddy, so the email platform had to coexist with that site. Oracle's outbound SMTP restrictions and the small VM's memory were major design constraints.

The result is a modular mail stack: Cloudflare handles public inbound routing, Postfix accepts SMTP and submits outgoing messages, Dovecot authenticates users and exposes IMAP, Roundcube is the webmail application, Rspamd classifies mail, Sieve sorts it, DNSExit handles outbound relay and DKIM signing, and Restic encrypts backups before Rclone transfers them to Google Drive.

1.1 Prerequisites and example environment

You need a domain whose DNS you control, a Linux VM with public ingress, an administrator SSH key, a verified forwarding destination, an authenticated SMTP relay, and off-server backup storage. Use a test mailbox first. This guide uses a Debian-style Ubuntu host, Dovecot 2.4 configuration syntax, and the Roundcube 1.7 public document root. Confirm package and PHP versions on your host before applying paths or service names.

Role Example
Public domain example.com
Webmail and mail host mail.example.com
Internal SMTP delivery domain inbox.example.com
First mailbox [email protected]
VM address for examples 192.0.2.10
Mail storage /var/vmail/<local-part>/Maildir

Replace the documentation domains, IP addresses, provider values, and credential placeholders throughout this tutorial. Check each service before proceeding to the next phase. On an existing installation, back up the affected configuration and inspect it before applying a fresh-install command.

1.2 Example account directory

The core build was tested with one mailbox. Section 20 shows how to add two independent accounts. Run its acceptance checks for every mailbox you provision.

1.3 What to verify before relying on this setup

The original build confirmed incoming and outgoing delivery, secure IMAP, an incoming forwarded copy, local spam classification, and the presence of encrypted backup snapshots. Local delivery tests also exercised Inbox and Junk. Repeat those checks on your server.

Keep the account-expansion checks, a full restore rehearsal, a certificate-renewal dry run, and an inbound test for a forged classification header on your own acceptance checklist. A working mailbox alone does not establish that these paths work.

2. Email fundamentals: what happens when a message is sent

2.1 SMTP, IMAP, POP3, and HTTP are different protocols

An email service has several jobs. Sending and accepting mail use SMTP (Simple Mail Transfer Protocol). Reading and synchronizing mail typically use IMAP (Internet Message Access Protocol). POP3 is another retrieval protocol, not needed in this design. Roundcube exposes a normal HTTPS web application to browsers, then communicates with IMAP and SMTP servers on the user's behalf.

Port Protocol / purpose Security and access in this build
TCP 25 SMTP, server-to-server delivery Incoming to Postfix, opportunistic STARTTLS, no public authentication or arbitrary relaying
TCP 587 SMTP submission by authenticated users STARTTLS required before authentication; uses Dovecot SASL
TCP 993 IMAP over TLS (IMAPS) Encrypted from the start of the connection
TCP 443 HTTPS Caddy serves website and Roundcube
TCP 80 HTTP Caddy's HTTP-to-HTTPS redirect / certificate challenges
TCP 22 SSH Administration and private tunnels
TCP 465 Implicit-TLS SMTP submission Not enabled; port 587 is used instead
TCP 143 IMAP, optionally STARTTLS Disabled in this setup
TCP 110/995 POP3/POP3S Not needed
TCP 11332 Rspamd Milter proxy Loopback only
TCP 11334 Rspamd controller Loopback only, accessed through SSH tunnel
TCP 3000 SvelteKit/Bun app Loopback only, proxied by Caddy
Unix socket Dovecot SASL and LMTP, PHP-FPM Local IPC, not a network port

STARTTLS means the application connection begins as a protocol exchange, then negotiates TLS before continuing. Implicit TLS begins with a TLS handshake immediately. Both can be secure when certificate validation and the required encryption policy are correctly configured. Port 25 generally must accept mail from systems across the Internet, so demanding TLS from every sending server can cause delivery problems; port 587 is controlled submission and should require it.

2.2 The actors in a mail system

  • MUA (Mail User Agent): the interface a human uses, e.g. Apple Mail, Thunderbird or Roundcube.
  • MSA (Mail Submission Agent): an authenticated endpoint accepting outgoing mail from a user. Here it is Postfix on port 587.
  • MTA (Mail Transfer Agent): receives and relays SMTP messages. Postfix, Cloudflare's receiving service, and DNSExit's relay participate in this role.
  • MDA/LDA (Mail Delivery Agent): places a received message in a mailbox. Initially this was Postfix's virtual delivery agent; after migration, Dovecot LMTP and Sieve take over.
  • MRA/access server: Dovecot implements the IMAP service through which clients read and modify stored messages.
  • Milter: a mail filter interface used by Postfix to ask another process to inspect a message. Rspamd communicates over Milter and returns spam classifications and header modifications.

These roles need not be separate machines. A single process may implement several, and this system intentionally reuses one inexpensive VM.

2.3 Envelope addresses versus message headers

An SMTP transaction has envelope commands such as MAIL FROM and RCPT TO. The email data also contains human-visible fields such as From:, To: and Subject:. These are not necessarily the same. Bcc, mailing lists, and forwarding all demonstrate why.

For example, Gmail sends a message with visible To: [email protected]. Cloudflare rewrites the delivery envelope to [email protected], but the original visible recipient remains reader's public address. Postfix uses the envelope recipient, not a string in the visible To header, to choose local delivery. The Worker must likewise use message.to, the actual envelope recipient. Using a visible header could mix deliveries, ignore Bcc, or allow forged routing information.

A Return-Path added during final delivery records the relevant envelope sender. It may differ from the original visible From. Delivery failures are generally returned to the envelope sender, which may have been rewritten by a forwarding service.

2.4 Queues, retries, and SMTP response codes

Postfix is queue-based. Once a receiving server accepts responsibility for a message, it can store the message in a queue until downstream delivery succeeds. A transient 4xx response generally leads to retries. A permanent 5xx rejection normally results in a failure notification instead of indefinite retries. 250 means the particular SMTP command or delivery step succeeded; it does not establish that a message landed in a user's Inbox rather than Junk.

The build encountered both classes of error: DNSExit temporarily returned 454 4.7.1 DATA rejected ... FAIL [0 of 0] after authentication, then delivery worked on retry. Cloudflare returned 550 5.1.1 Address does not exist for the public reader address because the corresponding route was missing. The latter required adding/activating the route and resending the message.

2.5 Maildir and virtual users

Maildir stores each message as an individual file. A mailbox has tmp, new, and cur directories: temporary construction, newly delivered messages, and messages that have been seen or moved into the current set. IMAP flags are often encoded in filenames; Dovecot also maintains index/control files. Special folders such as Junk and Sent have their own Maildir structures, typically .Junk and .Sent under the mailbox root.

A virtual email account is not a Linux shell account. Instead, an authentication database records an email address, password hash, UID/GID and home directory. All mailboxes here are owned by a single restricted service account, vmail. Dovecot selects the home associated with the login. This makes additional accounts easy to create without adding SSH-enabled users, but the shared operating-system identity means this is not a strong multi-tenant sandbox for untrusted customers.

2.6 SPF, DKIM, DMARC, ARC, and SRS

Mechanism What it does What it does not prove
SPF DNS policy authorizing hosts to send for an SMTP envelope domain The visible From address is authentic or the body is unmodified
DKIM Signs selected headers and body content with a private key; receivers verify a DNS public key The message is safe or the human sender is trustworthy
DMARC Requires aligned SPF or DKIM success with the visible From domain and publishes handling/reporting policy Every recipient will place the mail in Inbox
ARC Allows intermediaries to record and seal earlier authentication results Every forwarder is trustworthy; the receiver must evaluate the chain
SRS Rewrites an envelope sender during forwarding so the forwarder's sending IP can pass SPF and bounces can be routed Replaces the original From address or independently establishes DMARC alignment
TLS Encrypts a connection between two adjacent systems End-to-end encryption of mail content at all providers or storage locations

Authentication and spam filtering complement each other. An authenticated phishing email is still dangerous. Conversely, a legitimate forwarded message can look unusual because its envelope or sending IP has changed. The recorded Rspamd result demonstrates correct treatment of the Cloudflare forwarding path.

3. Architecture and design decisions

3.1 Incoming delivery

External sender
  -> Cloudflare public MX servers
  -> recipient-based Worker
     -> verified Gmail mailbox (incoming copy)
     -> internal address at inbox.example.com
        -> Oracle Postfix:25 -> Rspamd (classification)
        -> Dovecot LMTP -> Sieve -> Maildir Inbox or Junk
        -> Dovecot IMAPS -> Roundcube or other IMAP client

The two forwarding branches are independent. Gmail is a convenient duplicate destination, not an atomic replica of the local mailbox. It does not mirror flags, folder moves, drafts, sent mail, contacts or preferences. A failure of one forwarding branch does not guarantee a retry of that branch. The encrypted Restic backup is the actual recovery mechanism.

3.2 Outgoing delivery

Browser → Caddy → Roundcube → Postfix submission on TCP 587
Mail client ────────────────→ Postfix submission on TCP 587
Postfix → Dovecot authentication via a private Unix socket
Postfix → authenticated SMTP relay → recipient mail server

The envelope sender is authorized through Postfix's sender-login map. DNSExit signs outgoing mail for the verified domain. Outgoing email bypasses the incoming Rspamd Milter in this configuration. Roundcube or a mail client saves a copy to Sent through IMAP; SMTP alone is not an automatic Sent-folder archive.

3.3 Why these choices were made

Decision Rationale / trade-off
Cloudflare handles public inbound MX Provides an incoming routing layer and duplication to Gmail without replacing the local mailbox. Adds an external dependency.
Separate internal subdomain Prevents routing a message sent to the public address back into the same Cloudflare rule indefinitely.
DNSExit for outgoing Works around Oracle outbound TCP 25 restrictions through port 587. Provider quota and account renewal apply.
Existing Caddy instead of Nginx/Apache No second HTTP daemon competing for ports 80/443; preserves SvelteKit site.
Dovecot + Maildir + passwd files Straightforward for a small number of personal accounts; no separate mailbox database engine.
SQLite for Roundcube Small local application database with no resident database server process.
PHP-FPM on-demand pool Starts application workers only when requests arrive, appropriate for a memory-limited VM.
Rspamd without Redis/ClamAV Provides authentication, content and reputation checks with modest memory. No Redis-based Bayesian learning or antivirus attachment scanning.
Sieve instead of deleting spam Suspicious messages remain recoverable in Junk. Protects important academic/professional mail against false positives.
Restic + Rclone Client-side encrypted, deduplicated off-server snapshots, independent of the mail delivery system.
systemd timers Automation with a visible service history, calendar schedule and missed-run catch-up.

3.4 Service and file inventory

Service Main configuration / data Role
Caddy /etc/caddy/Caddyfile HTTPS for both sites, reverse proxy and FastCGI
Postfix /etc/postfix/main.cf, /etc/postfix/master.cf SMTP, queue, relay and transport policies
Postfix recipient map /etc/postfix/vmailbox + .db Recognized internal recipients
Postfix sender map /etc/postfix/sender_login_maps + .db SMTP envelope sender authorization
Postfix relay credentials /etc/postfix/relay_passwd + .db Secret outbound SASL credentials
Dovecot /etc/dovecot/dovecot.conf IMAP, SASL, LMTP, namespaces
Dovecot passdb /etc/dovecot/virtual-users Password hashes and virtual account records
Dovecot userdb /etc/dovecot/mailbox-users Public and internal address-to-home lookup
Sieve /etc/dovecot/sieve/spam-filter.sieve Global delivery filtering rule
Maildir /var/vmail/ Actual messages and folder metadata
Roundcube /var/www/roundcube Webmail application
Roundcube configuration /var/www/roundcube/config/config.inc.php IMAP/SMTP/TLS and application settings
Roundcube SQLite /var/lib/roundcube/roundcube.sqlite Contacts, identities, preferences and sessions
PHP-FPM /etc/php/8.5/fpm/pool.d/roundcube.conf Dedicated worker pool and socket
Rspamd /etc/rspamd/local.d/, /var/lib/rspamd Filter configuration and data
Fail2ban /etc/fail2ban/jail.d/, /etc/fail2ban/filter.d/ Login failure monitoring and IP bans
Certbot /etc/letsencrypt/, /root/.secrets/cloudflare.ini Mail TLS certificates and DNS challenge
Firewall iptables and /etc/iptables/ if persisted Host network access policy
Backup /usr/local/sbin/mail-backup, /usr/local/sbin/mail-restic, /etc/mail-backup/ Encrypted snapshots and remote credentials
Monitoring /usr/local/sbin/mail-health Health checks and systemd journal output
Cloud services OCI dashboard, Cloudflare dashboard, DNSExit, Google OAuth project External settings and accounts, not fully represented by VM files

4. Oracle Cloud and Linux foundation

4.1 Create or reuse the VM

The platform reused an Oracle VM.Standard.E2.1.Micro Ubuntu instance instead of introducing another server. The VM already served a SvelteKit/Bun site. The public IP recorded in the build is 192.0.2.10, and the internal OS hostname is example-vm. The hostname visible in SMTP is deliberately set separately to mail.example.com.

For a rebuild, select an available eligible free shape in the appropriate OCI region, use Ubuntu and a public subnet with an Internet route, assign a public IPv4 address, and inject the administrator's SSH public key. Do not expose a password-based root SSH login just to make administration easier. OCI has two firewall layers relevant to the build: security lists or network security groups at the VCN/VNIC level, and Linux firewall rules within the VM. A port works only if both permit traffic and a process is actually listening.

Example SSH command from the administrator's Mac:

chmod 600 ~/.ssh/example-mail-key
ssh -i ~/.ssh/example-mail-key [email protected]

Keep the private key on a trusted device. The public key, not the private key, is installed on the VM. Ideally store the local private key in a protected ~/.ssh directory, backed up safely.

Useful discovery commands:

cat /etc/os-release
hostname
uname -m
free -h
swapon --show
df -h /
lsblk
sudo ss -lntup
sudo iptables -L INPUT -n -v --line-numbers

4.2 Understand memory and swap

The final machine had 951 MiB RAM and an 8 GiB swapfile. Swap is disk-backed memory; it is not equivalent to having 8 GiB of fast RAM. It can protect against short spikes and out-of-memory kills but sustained swapping can make webmail and delivery slow. Linux also uses spare memory for filesystem caching. MemAvailable is more useful than the raw free column when determining whether there is memory pressure.

The swapfile was already present. Only on a fresh machine with adequate disk and no existing /swapfile, a conventional creation procedure is:

# Fresh VM only: do NOT overwrite an existing active swapfile.
sudo fallocate -l 8G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Add /swapfile none swap sw 0 0 to /etc/fstab once if it is not already present. Some filesystems require a different creation procedure; check swapon --show and filesystem compatibility. Never disable swap just to make the used counter zero. The final diagnostics showed only about 203 MiB occupied, which was acceptable in that snapshot.

4.3 Prepare packages and preserve the website

sudo apt update
sudo apt install -y ca-certificates curl openssl dnsutils swaks \
  postfix dovecot-core dovecot-imapd iptables-persistent

On a fresh Postfix installation, the package may ask for an installation type and system mail name. Use the mail domain and then explicitly set the role in Section 6; the package wizard alone does not create the intended virtual mailbox setup. Do not overwrite a preexisting working mail configuration. Check apt-cache policy and installed versions before relying on version-specific commands.

The Caddy website block is retained throughout the setup:

example.com, www.example.com {
    encode zstd gzip
    reverse_proxy 127.0.0.1:3000
}

Caddy receives public HTTPS and proxies to the local Bun application. Postfix and Dovecot use different ports, so they do not compete with Caddy. Roundcube is added as a separate virtual host in Section 12. Verify the website after each major change rather than assuming a reload is harmless.

4.4 Oracle port 25 restriction and why it mattered

An inbound SMTP connection to port 25 and an outbound connection from the VM to a remote MTA's port 25 are different traffic directions. OCI's outbound restriction was the reason for using DNSExit on TCP 587. It does not mean incoming SMTP should be moved to 587; public MX delivery uses TCP 25.

During the build, port 25 was reachable from multiple external test nodes, while connection attempts from the administrator's network and another test location failed. This was consistent with network-specific outbound SMTP restrictions. A single failed test did not establish that the receiving VM was unreachable everywhere. Test from independent networks and check OCI ingress, host firewall, socket listener and SMTP response separately.

5. DNS and Cloudflare Email Routing

5.1 Understand DNS records

An A record maps a name to an IPv4 address; AAAA maps to IPv6. A CNAME aliases one name to another. MX records tell a sending MTA which hostname accepts mail for a domain, with lower numeric priority preferred. TXT records publish authentication policies and verification strings.

DNS is not a mail store and does not create a mailbox. The MX record directs SMTP traffic to a receiving service; that service then needs a route or a recipient lookup entry.

5.2 DNS design used by the platform

Type Name in Cloudflare zone Value / purpose Proxy mode
A @ 192.0.2.10, website origin Proxied (as recorded)
CNAME www Root site name / existing website alias Proxied
A mail 192.0.2.10, SMTP/IMAP and webmail DNS only
MX @ Three Cloudflare-generated MX records DNS only / managed by Email Routing
MX inbox Priority 10, mail.example.com DNS only
TXT @ Combined SPF authorizing Cloudflare forwarding and DNSExit DNS only
CNAME relay._domainkey dkim.dnsexit.com as provided by DNSExit DNS only
TXT _dmarc DMARC monitoring policy, p=none DNS only
TXT / CNAME Cloudflare-generated DKIM or verification records Retain exactly as provided DNS only

The exact three Cloudflare MX names, current DNS TTLs and complete published TXT strings were not printed in the final build logs. Let Cloudflare generate its own MX and verification records; do not substitute guessed values. The expected combined SPF was:

v=spf1 include:_spf.mx.cloudflare.net include:dnsexit.com ~all

Keep a single SPF record at the root, merging legitimate providers rather than publishing two v=spf1 records. DNS SPF evaluation has a lookup limit; verify it if adding more providers. The ~all softfail at the end is an intentional initial policy, not a requirement for every future configuration. Other TXT records can coexist with SPF.

Cloudflare's ordinary HTTP reverse proxy does not carry standard SMTP/IMAP traffic. That is why the mail host must be DNS only in this design. It also means the origin IP is public; do not assume the proxied website's IP is hidden when a mail hostname reveals the same IP. Restrict services at the origin accordingly.

No A record is strictly required for the inbox label when its MX points at a hostname that has an A record. Mail sent to [email protected] resolves through the subdomain MX to mail.example.com. It does not follow the public root domain's MX records back to Cloudflare. This separation prevents forwarding loops.

5.3 Verify DNS from the terminal

dig A mail.example.com +short
dig MX example.com +short
dig MX inbox.example.com +short
dig TXT example.com +short
dig CNAME relay._domainkey.example.com +short
dig TXT relay._domainkey.example.com +short
dig TXT _dmarc.example.com +short

Check both recursive resolution and dashboard values if changes have not propagated. DNS records can be cached until TTL expiry. Do not delete the Cloudflare MX records while the domain's incoming routing depends on them. The actual outbound DKIM signature used selector relay, and the real incoming Cloudflare signatures used selector cf2024-1 during this build; selectors may change as providers rotate keys.

5.4 Activate Email Routing

In Cloudflare, select the domain, open Email Routing, and follow the wizard to add the required MX/TXT records. Configure the external Gmail destination and later the internal SMTP address. Each forwarding destination must be verified. Public address routing rules are separate from destination addresses: [email protected] is a rule that invokes a Worker, while [email protected] and [email protected] are verified destinations the Worker forwards to.

Section 9 covers the Worker once local SMTP delivery is available. This order matters: Cloudflare's verification email to an internal address cannot arrive until Postfix can accept that internal domain and recipient.

6. Postfix: incoming SMTP and virtual mailboxes

6.1 Why Postfix needs a recipient map

Postfix must distinguish three things: domains it accepts as local, recipients it recognizes, and messages it may relay to remote destinations. Without strict limits, a public SMTP service could become an open relay abused by spammers. The initial incoming Postfix configuration treated only the internal delivery domain as a virtual mailbox domain and accepted only known recipients. It did not claim the public root domain as local, because the root is handled by Cloudflare.

Create a restricted vmail operating-system account on a fresh installation only. Check the existing user first:

getent passwd vmail
getent group vmail
id vmail

If absent, a suitable system-account setup is:

sudo groupadd --system vmail
sudo useradd --system --gid vmail --home-dir /var/vmail \
  --shell /usr/sbin/nologin vmail
sudo install -d -o vmail -g vmail -m 750 /var/vmail

Do not force UID/GID 5000/5000 on a new machine if those numeric IDs are already used. On a new setup determine the actual IDs; on a recovery either recreate the original IDs safely or remap file ownership and configuration consistently. The original build used UID 5000/GID 5000.

Create reader's Maildir on a fresh installation:

sudo install -d -o vmail -g vmail -m 700 \
  /var/vmail/reader /var/vmail/reader/Maildir \
  /var/vmail/reader/Maildir/cur \
  /var/vmail/reader/Maildir/new \
  /var/vmail/reader/Maildir/tmp

The parent and children should be accessible to vmail but not arbitrary shell users. Do not make /var/vmail world-readable just to inspect messages. sudo ls can read protected files; a glob expanded by the invoking shell before sudo may not. For example, use sudo sh -c 'ls -l /var/vmail/reader/Maildir/new/*' if necessary. Raw email contains private data; avoid printing it into shared logs.

6.2 Initial Postfix configuration

Back up /etc/postfix before modifying it. postconf -e 'key=value' writes a setting in main.cf without requiring a full replacement. Using the actual UID/GID for this host, the initial state was equivalent to:

# /etc/postfix/main.cf - initial incoming delivery settings
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
inet_protocols = ipv4
mydestination = localhost
mynetworks = 127.0.0.0/8

virtual_mailbox_domains = inbox.example.com
virtual_mailbox_base = /var/vmail
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_transport = virtual
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000

smtpd_relay_restrictions = reject_unauth_destination
smtpd_reject_unlisted_recipient = yes
smtpd_sasl_auth_enable = no
disable_vrfy_command = yes

The virtual transport was used only during the initial phase. In the completed architecture it is replaced by LMTP in Section 17; retain the virtual_mailbox_domains and virtual_mailbox_maps so Postfix can still validate recipients before accepting mail. mydestination must not overlap the virtual mailbox domain, nor inadvertently make the root domain a local Unix-user delivery domain.

The initial map:

# /etc/postfix/vmailbox
[email protected] reader/Maildir/

The right-hand side in the initial virtual delivery phase is relative to virtual_mailbox_base. After the LMTP migration the existence of the key is what matters for recipient recognition; Dovecot's userdb chooses the actual home.

sudo postmap hash:/etc/postfix/vmailbox
sudo postmap -q [email protected] hash:/etc/postfix/vmailbox
sudo postfix check
sudo systemctl reload postfix

postmap compiles the human-readable map into the backend database (typically .db). Editing only the text file does not necessarily update the lookups until postmap is run. Back up both the configuration and map sources; rebuild compiled maps on recovery rather than relying on binary compatibility.

6.3 Port 25 and relay restrictions

Configure the service-specific incoming policy so the public SMTP listener cannot be used for arbitrary outgoing relay. The build used the following explicit overrides:

sudo postconf -P \
  'smtp/inet/smtpd_relay_restrictions=reject_unauth_destination' \
  'smtp/inet/smtpd_sasl_auth_enable=no' \
  'smtp/inet/smtpd_reject_unlisted_recipient=yes' \
  'smtp/inet/relay_domains='
sudo postfix check && sudo systemctl reload postfix

postconf -P changes service parameters in master.cf; this is different from postconf -e, which changes global main.cf settings. Validate effective settings with both commands. The earlier build had a local port 25 test that accepted an external RCPT before explicit overrides; localhost acceptance alone does not establish an Internet-open relay. The following controlled tests are part of the required acceptance check, not a claim that every external relay check was captured.

sudo postconf -P smtp/inet/smtpd_relay_restrictions
sudo postconf -P smtp/inet/smtpd_sasl_auth_enable
swaks --server 127.0.0.1 --port 25 --from [email protected] \
  --to [email protected] --quit-after RCPT
swaks --server 127.0.0.1 --port 25 --from [email protected] \
  --to [email protected] --quit-after RCPT
swaks --server 127.0.0.1 --port 25 --from [email protected] \
  --to [email protected] --quit-after RCPT

Expected: known internal recipient accepted; unknown internal recipient and unrelated external relay rejected. Repeat the unrelated-domain RCPT test from a genuinely external network capable of outbound port 25. --quit-after RCPT avoids actually sending a test message. Do not weaken relay restrictions to solve delivery issues. If a new mailbox is rejected, check the map instead.

7. TLS certificates using Certbot and Cloudflare DNS

7.1 Why we need certificates outside Caddy

Caddy terminates HTTPS for the website and webmail. It does not terminate the direct SMTP and IMAP connections handled by Postfix and Dovecot. We therefore obtained a separate trusted certificate for mail.example.com through Certbot. The two certificate managers can renew independently, with different expiration dates, without conflict.

DNS-01 validates domain control by temporarily publishing a DNS TXT challenge record rather than starting another HTTP server. This avoids competing with the already-running Caddy for port 80. The Cloudflare API token should be restricted to the required DNS zone and permissions; it is a powerful secret even when scoped.

7.2 Install Certbot and DNS plugin

For the apt-based installation used in this guide:

sudo apt install -y certbot python3-certbot-dns-cloudflare
sudo install -d -m 700 /root/.secrets
sudo nano /root/.secrets/cloudflare.ini

File format (placeholder only):

dns_cloudflare_api_token = REPLACE_WITH_SCOPED_TOKEN

Set restrictive permissions and request the certificate:

sudo chmod 600 /root/.secrets/cloudflare.ini
sudo certbot certonly --dns-cloudflare \
  --dns-cloudflare-credentials /root/.secrets/cloudflare.ini \
  --dns-cloudflare-propagation-seconds 60 \
  -d mail.example.com
sudo certbot certificates

Follow the prompts and use the real domain owner contact details. If a certificate already exists, inspect its name and lineage rather than requesting another needlessly. The recorded certificate lineage was /etc/letsencrypt/live/mail.example.com/ and the initial expiration was February 27, 2027. Current expiration is whatever the live certificate reports, not that historical date.

The live files are normally symbolic links to versioned files in the archive directory. fullchain.pem supplies the leaf certificate and intermediate chain; privkey.pem is the private key. The private key must not be distributed to clients or made world-readable.

7.3 Configure Postfix TLS

sudo postconf -e \
  'smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem' \
  'smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem' \
  'smtpd_tls_security_level = may'
sudo postfix check && sudo systemctl reload postfix

may is the incoming server-side policy; the submission listener will override it with encrypt. smtpd_* parameters describe the SMTP server, while smtp_* parameters describe Postfix as an SMTP client connecting to another server. Confusing them can accidentally leave outgoing relay connections unprotected or require encryption from all incoming senders.

Test certificate presentation against the hostname, even when connecting locally:

openssl s_client -starttls smtp -connect 127.0.0.1:25 \
  -servername mail.example.com \
  -verify_hostname mail.example.com -verify_return_error </dev/null

Connecting to 127.0.0.1 and asking the client to validate a certificate for the IP address rather than the DNS hostname can fail correctly. That does not mean the certificate is invalid for mail.example.com. Always verify the DNS name, trust chain and expiry rather than switching certificate validation off.

8. Dovecot: secure IMAP and virtual authentication

8.1 Dovecot 2.4 syntax and authentication model

Dovecot has a password database (passdb) to verify credentials and a user database (userdb) to return mailbox identity, UID, GID and home. The initial build used one passwd-file for both. Later LMTP required a separate userdb so both the public login and the internal forwarding address resolve to the same mailbox, without making the internal address another login.

A passwd-file record is colon-separated, similar to a Unix passwd record. In this setup the public address is the username, followed by a password hash with its scheme, the service UID/GID, a comment field, home directory and remaining fields. A password hash verifies a supplied password without storing the original plaintext password in the file. SHA512-CRYPT is the recorded scheme used in the build, not a claim that it is the strongest available password hashing scheme. Use long unique passwords and consider a supported stronger scheme when intentionally upgrading authentication.

Generate a password hash privately on the server (example for a new mailbox):

sudo doveadm pw -s SHA512-CRYPT

This interactive command asks for the password. In the original build the working alternative used Python getpass and openssl passwd -6 -stdin to avoid a password prompt/quoting problem. Both can produce an appropriate hash, but doveadm pw includes the scheme prefix while openssl passwd -6 produces the $6$... hash alone. Do not double-prefix it.

The real /etc/dovecot/virtual-users should contain a record in this form (the hash below is intentionally not a valid credential):

[email protected]:{SHA512-CRYPT}$6$REPLACE_WITH_REAL_HASH:5000:5000::/var/vmail/reader::
sudo chown root:dovecot /etc/dovecot/virtual-users
sudo chmod 640 /etc/dovecot/virtual-users

Do not use an example hash literally. Do not display actual hashes in support screenshots. The IMAP password is distinct from the Linux SSH key, Gmail password, DNSExit relay credentials and Google Drive/Restic secrets.

8.2 Initial Dovecot configuration

The build used a minimal Dovecot 2.4 configuration. This is a reconstruction of that state, before LMTP and Sieve were added. On the live system use the final configuration in Section 17 together with the relevant existing namespace settings.

# /etc/dovecot/dovecot.conf (initial IMAP phase)
dovecot_config_version = 2.4.0
dovecot_storage_version = 2.4.0
protocols = imap
listen = 0.0.0.0

mail_driver = maildir
mail_path = ~/Maildir
first_valid_uid = 5000
last_valid_uid = 5000

auth_mechanisms = plain login
auth_allow_cleartext = no
auth_verbose = yes

passdb passwd-file {
    passwd_file_path = /etc/dovecot/virtual-users
}
userdb passwd-file {
    passwd_file_path = /etc/dovecot/virtual-users
}

ssl = required
ssl_min_protocol = TLSv1.2
ssl_server_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_server_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem

service imap-login {
    inet_listener imap {
        port = 0
    }
    inet_listener imaps {
        port = 993
        ssl = yes
    }
}

service auth {
    unix_listener /var/spool/postfix/private/auth {
        mode = 0660
        user = postfix
        group = postfix
    }
}

namespace inbox {
    inbox = yes
    separator = /
    mailbox Drafts {
        auto = subscribe
        special_use = \Drafts
    }
    mailbox Sent {
        auto = subscribe
        special_use = \Sent
    }
    mailbox Junk {
        auto = subscribe
        special_use = \Junk
    }
    mailbox Trash {
        auto = subscribe
        special_use = \Trash
    }
    mailbox Archive {
        auto = subscribe
        special_use = \Archive
    }
}

The mail_path uses ~ to expand to the virtual user's home. Dovecot runs mail access using that user's numeric UID/GID, which must match file ownership. first_valid_uid and last_valid_uid limit which UIDs can be used; the single virtual UID is intentional. The namespace sets the hierarchy separator and advertises standard folder roles so clients can discover Sent, Junk, etc. Automatic subscription makes the folders appear in IMAP clients. The actual namespace syntax was configured during the initial build; confirm with doveconf -n on the live host.

The PLAIN and LOGIN SASL mechanisms transmit credentials in a form that requires a secure transport. TLS is therefore mandatory. The auth socket is shared with Postfix, but it is a local Unix socket under Postfix's spool, not a new public authentication port. The Dovecot version flags protect storage/configuration compatibility; check documentation when migrating between 2.3 and 2.4.

8.3 Validate login and mailbox access

sudo doveconf -n
sudo systemctl enable --now dovecot
sudo systemctl restart dovecot
sudo systemctl is-active dovecot
sudo doveadm auth login [email protected]
sudo doveadm user [email protected]
sudo doveadm mailbox list -u [email protected]
sudo doveadm mailbox status -u [email protected] 'messages unseen' INBOX

Enter the mailbox password interactively when requested. The first build had repeated password mismatches; Dovecot logs isolated the issue, and safely generating a new hash solved it. Four existing messages were confirmed at the initial stage. Keep auth_debug_passwords disabled; detailed authentication debug logging should be temporary.

IMAP connection test with real TLS hostname verification:

curl --resolve mail.example.com:993:127.0.0.1 \
  --url 'imaps://mail.example.com/INBOX' \
  --user '[email protected]'

curl prompts for the password if it is omitted. Do not put a password on the command line where shell history or process inspection can expose it. A successful login proves credentials and mailbox lookup work; it does not establish external connectivity until the cloud and host firewalls allow port 993.

9. Cloudflare Worker: duplicate incoming mail

9.1 Verify forwarding destinations

In the Cloudflare dashboard, add and verify:

[email protected]
[email protected]

The internal destination's verification email arrives on Oracle via the subdomain's MX. Before webmail is ready, it can be viewed through IMAP or by carefully reading the relevant Maildir message as root. The Gmail destination's verification email arrives in Gmail. If a verification message lands in Junk, inspect it and follow the expected official link.

A destination verification proves control of that address. It does not create a public routing rule for [email protected]. Both are required.

9.2 Worker implementation (single-account build)

Create a Cloudflare Worker called example-mail-router with an email event handler. The following is a reconstruction of the working single-account logic, which awaited both forwarding outcomes and logged partial failures. It is not a byte-for-byte export from Cloudflare.

export default {
	async email(message, env, ctx) {
		const destinations = ['[email protected]', '[email protected]'];

		const results = await Promise.allSettled(
			destinations.map((destination) => message.forward(destination))
		);

		results.forEach((result, index) => {
			if (result.status === 'fulfilled') {
				console.log(`Forwarded to ${destinations[index]}`);
			} else {
				console.error(`Forwarding failed for ${destinations[index]}`, String(result.reason));
			}
		});

		if (results.every((result) => result.status === 'rejected')) {
			throw new Error('All forwarding destinations failed');
		}
	}
};

message.forward() instructs Cloudflare to forward the original email to a verified destination. Promise.allSettled() waits for every promise rather than rejecting early as Promise.all() does. This allows the Worker to record both outcomes. The implementation throws when both forwarding calls fail; the exact upstream SMTP failure/retry behavior depends on Cloudflare. This is not a durable per-recipient retry queue and does not provide exactly-once duplication. If one forwarding succeeds, the failed branch can remain missing. Use Worker logs and independent delivery tests to catch such issues.

Create a public routing rule:

Custom address Action Worker
[email protected] Send to a Worker example-mail-router

An initial test route used [email protected]. It worked when the test address matched the rule, but the real address initially returned 550 5.1.1 Address does not exist. Adding or activating the real public rule fixed the issue. A route should be disabled or explicitly included in the recipient-specific Worker table if no longer used.

9.3 Verify a complete inbound delivery

Send from an independent external account to the public address. Check Roundcube/IMAP and the forwarding Gmail mailbox. Inspect the Cloudflare Email Routing activity log and Postfix logs:

sudo journalctl --since '10 minutes ago' | grep -Ei 'postfix|dovecot'
sudo postqueue -p

A successful external delivery to Postfix is distinct from a successful Gmail copy. The initial Gmail forwarded copy sometimes landed in spam even with SPF, DKIM, DMARC and ARC passing; Cloudflare spam score was zero. There was no evidence identifying a single cause. Mark a legitimate copy as not spam and observe future delivery; do not weaken authentication based on one spam placement. In tests, avoid using the same Gmail account as both original sender and forwarding destination, because Gmail may deduplicate or suppress its own forwarded copy.


10. DNSExit: outgoing SMTP relay and authentication

10.1 Why direct delivery was not selected

A normal MTA can look up a recipient domain's MX and contact it on TCP 25. Cloud VMs frequently have outbound port 25 restrictions and new or low-reputation IP addresses may have poor deliverability. Running a direct outbound MTA also requires attention to reverse DNS (PTR), HELO identity, IP reputation, abuse control and recipient acceptance policies. The project intentionally avoided this complexity by using an authenticated relay on port 587.

DNSExit was selected after free alternatives proved unsuitable for the owner's availability and budget constraints. Its free plan in the recorded setup allowed 25 recipients per day, shared across the account, with renewal required every 180 days. The account dashboard initially showed November 29, 2026 through May 28, 2027. Verify current terms, usage, renewal date and acceptable-use limits in the provider dashboard; the plan is an external service and can change. Sending to several recipients can consume several units of quota even when it is one message.

The relay verifies credentials, accepts outgoing mail from Postfix over TLS, and sends it onward using its own delivery infrastructure. It also signs the message using a DKIM key for the verified custom domain. The actual outbound test later confirmed that the relay selector was working.

10.2 Domain verification and DNS

Add example.com as an authorized sender domain in DNSExit's mail relay dashboard. Follow its instructions for SPF and DKIM. The intended DNS records were:

@ TXT "v=spf1 include:_spf.mx.cloudflare.net include:dnsexit.com ~all"
relay._domainkey CNAME dkim.dnsexit.com
_dmarc TXT "v=DMARC1; p=none"

These are the configuration values used during setup, not a guarantee that the provider's instructions will never change. If the domain already has an SPF record, merge the DNSExit inclusion into that existing SPF record. Do not remove Cloudflare's forwarding authorization. The CNAME lets DNSExit publish and rotate the public DKIM key; no locally generated OpenDKIM signing key is required for the demonstrated DNSExit path.

10.3 Create the relay credential map

Install the SASL mechanisms used by Postfix's SMTP client if not already installed:

sudo apt install -y libsasl2-modules
sudo install -m 600 /dev/null /etc/postfix/relay_passwd  # fresh file only
sudo nano /etc/postfix/relay_passwd

On a running system do NOT execute the install command against the existing credential file: it would replace it. Instead edit the current file carefully. Enter the provider-issued relay login and password, not the mailbox password.

[relay.dnsexit.com]:587 EXAMPLE_RELAY_LOGIN:REPLACE_WITH_DNSEXIT_RELAY_PASSWORD

Then build and protect the map:

sudo postmap hash:/etc/postfix/relay_passwd
sudo chown root:root /etc/postfix/relay_passwd /etc/postfix/relay_passwd.db
sudo chmod 600 /etc/postfix/relay_passwd /etc/postfix/relay_passwd.db

Postfix may cache the lookup or keep processes alive until reload. The plaintext source and its compiled map both contain sensitive credentials. Never include real values in a diagnostic output or an unencrypted backup.

10.4 Configure Postfix as an outbound SMTP client

sudo postconf -e \
  'relayhost = [relay.dnsexit.com]:587' \
  'smtp_sasl_auth_enable = yes' \
  'smtp_sasl_password_maps = hash:/etc/postfix/relay_passwd' \
  'smtp_sasl_security_options = noanonymous' \
  'smtp_sasl_tls_security_options = noanonymous' \
  'smtp_tls_security_level = secure' \
  'smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt' \
  'smtp_tls_loglevel = 1'
sudo postfix check && sudo systemctl reload postfix

The square brackets tell Postfix to contact the named relay directly rather than looking up its MX. The relayhost and password map keys must match exactly, including brackets and port. smtp_sasl_* is client-side SASL authentication; this is not the same as smtpd_sasl_* for users connecting to our Postfix server. The secure client TLS setting requires a trusted, matching certificate for the relay; this is stronger than merely requesting encryption. The CA bundle is the OS trust store.

Inspect configuration without printing secrets:

sudo postconf relayhost smtp_sasl_auth_enable smtp_tls_security_level smtp_tls_CAfile
openssl s_client -starttls smtp -connect relay.dnsexit.com:587 \
  -servername relay.dnsexit.com -verify_hostname relay.dnsexit.com \
  -verify_return_error </dev/null

10.5 Test local outbound queue delivery

The first outbound test was submitted locally to Postfix, independently of Roundcube. For example:

printf 'From: [email protected]\nTo: [email protected]\nSubject: Relay test\n\nTesting outgoing SMTP.\n' \
  | sudo sendmail -f [email protected] [email protected]
sudo postqueue -p
sudo journalctl --since '5 minutes ago' | grep postfix

Look for a queue ID and status=sent through relay.dnsexit.com. Do not repeatedly send test messages if the relay quota is exhausted.

The first relay attempts had successful SMTP AUTH (235), but a 454 4.7.1 DATA rejected: ... FAIL [0 of 0] response at DATA. A direct Swaks test isolated the failure to the relay's acceptance step, not our Postfix password map or TLS. The queued message eventually delivered after a retry, and a subsequent test also worked. The exact provider-side cause was not established. If it recurs, inspect plan activation/quota, sender-domain verification and the relay's own logs. A successful AUTH only proves credentials were accepted; a relay can still reject the sender, recipient, quota or message after authentication.

11. Authenticated submission and firewall security

11.1 Separate port 25 from port 587

Port 25 accepts mail for known internal recipients and must not offer unrestricted relay. Port 587 is specifically for authenticated local users sending to arbitrary recipients. Keeping the two policies separate avoids exposing an SMTP AUTH interface unnecessarily on port 25.

Dovecot's auth socket from Section 8 must exist and be owned appropriately for Postfix:

sudo ls -l /var/spool/postfix/private/auth
sudo postconf -a

postconf -a should list dovecot among available server-side SASL implementations. Configure submission using service-specific settings, as in the build:

sudo postconf -M 'submission/inet=submission inet n - n - - smtpd'
sudo postconf -P \
  'submission/inet/syslog_name=postfix/submission' \
  'submission/inet/smtpd_tls_security_level=encrypt' \
  'submission/inet/smtpd_tls_auth_only=yes' \
  'submission/inet/smtpd_sasl_auth_enable=yes' \
  'submission/inet/smtpd_sasl_type=dovecot' \
  'submission/inet/smtpd_sasl_path=private/auth' \
  'submission/inet/smtpd_sasl_security_options=noanonymous' \
  'submission/inet/smtpd_relay_restrictions=permit_sasl_authenticated,reject' \
  'submission/inet/smtpd_sender_login_maps=hash:/etc/postfix/sender_login_maps' \
  'submission/inet/smtpd_sender_restrictions=reject_authenticated_sender_login_mismatch' \
  'submission/inet/smtpd_recipient_restrictions=permit_sasl_authenticated,reject'

Create the sender-login mapping for a fresh single-account installation (do not truncate an existing multi-account map):

# /etc/postfix/sender_login_maps
[email protected] [email protected]
sudo postmap hash:/etc/postfix/sender_login_maps
sudo postfix check && sudo systemctl reload postfix
sudo ss -lntp | grep -E ':(25|587|993) '

The relay restrictions allow outgoing submission only after SASL authentication. The sender-login map binds the envelope sender to the authorized account, preventing an authenticated user from submitting mail with another registered account's envelope address. It does not independently enforce the human-visible From: header, which requires separate policy if users are untrusted. Roundcube identities are also configured to constrain ordinary use. For a service with unrelated customers, add and test explicit header-level sender authorization, rate limits and stronger isolation rather than treating this simple personal setup as a commercial multi-tenant MTA.

11.2 Test submission before opening it publicly

Unauthenticated test:

swaks --server 127.0.0.1 --port 587 --tls \
  --from [email protected] --to [email protected] --quit-after RCPT

Expected: rejection for unauthenticated relay. An initial test returned 554 as intended. Then test authentication and real outbound delivery with a known recipient:

swaks --server mail.example.com --port 587 --tls \
  --tls-verify --auth LOGIN --auth-user [email protected] \
  --auth-hide-password --from [email protected] \
  --to [email protected]

Enter the Dovecot password when prompted. Use the certificate hostname rather than the IP for certificate validation; the exact Swaks flags can vary by version (swaks --help). If the VM cannot hairpin to its own public IP, perform this test from the Mac after opening the port or use a controlled local hostname mapping. Never disable certificate checks as a permanent workaround. The recorded successful Roundcube-to-Gmail message later established that local submission and the outbound relay worked together.

11.3 Linux host firewall

The original host used iptables rather than UFW. Existing Oracle rules should not be flushed. Flushing the INPUT chain or changing its default policy without understanding Oracle's networking can disconnect SSH or expose services. Back up first:

sudo sh -c 'iptables-save > /root/iptables-before-mail.rules'
sudo iptables -L INPUT -n -v --line-numbers

The build inserted TCP 25, 587 and 993 rules before the terminal REJECT rule. A safe pattern for the already-existing chain layout is:

for PORT in 25 587 993; do
    if ! sudo iptables -C INPUT -p tcp --dport "$PORT" \
        -m conntrack --ctstate NEW -j ACCEPT 2>/dev/null; then
        RULE=$(sudo iptables -L INPUT -n --line-numbers \
          | awk '$2=="REJECT"{print $1; exit}')
        if [ -n "$RULE" ]; then
            sudo iptables -I INPUT "$RULE" -p tcp --dport "$PORT" \
              -m conntrack --ctstate NEW -j ACCEPT
        else
            echo 'REJECT rule not found; inspect firewall manually.' >&2
        fi
    fi
done
sudo iptables -L INPUT -n -v --line-numbers

This assumes the chain has the expected terminal rejection and other prerequisite rules. Do not apply this blindly to a different ruleset. The actual reported rules were:

Position in the original report Target Match
1 ACCEPT TCP 25, NEW
2 ACCEPT TCP 443
3 ACCEPT TCP 80
4 ACCEPT RELATED,ESTABLISHED
5 ACCEPT ICMP
6 ACCEPT loopback
7 ACCEPT TCP 22, NEW
8 ACCEPT TCP 587, NEW
9 ACCEPT TCP 993, NEW
10 REJECT unmatched traffic

Fail2ban can insert dynamic jump chains above the relevant ACCEPT rules when it bans an IP. They may be absent until the first ban. Persist the base rules without saving transient Fail2ban chains; on the original setup this was done with netfilter-persistent and a brief stop/start of Fail2ban while new cloud ingress was still closed:

sudo systemctl stop fail2ban
sudo netfilter-persistent save
sudo systemctl start fail2ban
sudo systemctl is-active fail2ban

On an exposed production server, plan this operation because stopping Fail2ban temporarily lifts its bans. Do not blindly restore an iptables dump from a different OCI machine. Check the active backend (iptables --version), IPv6 exposure, OCI-managed egress/network rules, and keep a working console or SSH session before changing rules. A default ACCEPT with a final unconditional REJECT is restrictive only while that final rule actually exists and is reached.

11.4 OCI security rules

Add stateful ingress rules in the security list or network security group attached to the VM, for TCP destination ports 25, 587 and 993. The original configuration used source CIDR 0.0.0.0/0, source port All, destination port as specified, Stateless = No. Keep the existing website ports 80/443 and SSH 22. Restrict SSH to trusted source addresses where practical and retain console recovery. Do not open Rspamd or the Bun application ports.

Stateful rules allow associated response traffic without creating independent reply rules. Verify the correct VNIC/subnet/NSG is affected. The OCI cloud firewall does not replace the Linux firewall.

From the Mac (outside SSH):

nc -4 -vz -G 5 mail.example.com 587
nc -4 -vz -G 5 mail.example.com 993
openssl s_client -starttls smtp -connect mail.example.com:587 \
  -servername mail.example.com -verify_hostname mail.example.com \
  -verify_return_error </dev/null

A successful TCP connection does not prove authentication; a successful TLS connection does not prove a mailbox exists. Test each layer. External IMAP/SMTP client setup instructions appear in Section 21; actual Apple Mail setup was not separately confirmed in the build record.

12. Roundcube: browser-based email

12.1 Why Roundcube is not the mail server

Roundcube is a PHP application that talks to IMAP and SMTP. It does not replace Dovecot or Postfix, and it does not store every message in SQLite. The real emails are in Maildir. SQLite holds webmail-specific state such as contacts, identities, preferences and sessions. Thus a Roundcube application failure need not stop incoming SMTP or an independent IMAP client from working.

Version 1.7.7 was selected from the official upstream release in the build because it included security fixes and the 1.6 branch was ending upstream maintenance. This is a historical choice, not a recommendation to install that version indefinitely. Check the official release page for a currently supported patched release and verify the installed version. The upstream installation documentation requires public_html as the document root in 1.7 and newer.

12.2 Install PHP and dependencies

sudo apt update
sudo apt install -y --no-install-recommends \
  php8.5-fpm php8.5-cli php8.5-common php8.5-mbstring \
  php8.5-xml php8.5-intl php8.5-curl php8.5-zip \
  php8.5-gd php8.5-sqlite3 sqlite3 unzip curl
php -v
sudo systemctl status php8.5-fpm --no-pager

The PHP-FPM package supplies a FastCGI service for Caddy, and extensions provide Unicode processing, XML, SQLite access, HTTP client support and attachment-related functionality. Installing Apache or a database daemon is unnecessary here. PHP package names are versioned; adapt them if rebuilding with a supported different PHP version. Verify Roundcube's PHP compatibility and requirements rather than blindly upgrading.

12.3 Install the complete Roundcube release

On a fresh system, download the selected complete release archive (includes vendor dependencies). Example using the historical version:

cd /tmp
curl -fLO https://github.com/roundcube/roundcubemail/releases/download/1.7.7/roundcubemail-1.7.7-complete.tar.gz
sha256sum roundcubemail-1.7.7-complete.tar.gz

Compare the digest/signature with trusted upstream release information before extracting; a locally printed checksum by itself does not authenticate the download. If installing a newer release, substitute the exact version and artifact filename. Do not extract over an existing deployment without following the upgrade guide and taking a backup.

sudo mkdir -p /var/www/roundcube
sudo tar -xzf /tmp/roundcubemail-1.7.7-complete.tar.gz \
  -C /var/www/roundcube --strip-components=1
sudo chown -R root:root /var/www/roundcube
sudo install -d -o www-data -g www-data -m 750 \
  /var/lib/roundcube /var/lib/roundcube/temp /var/log/roundcube
ls -lah /var/www/roundcube/public_html

Application code should be writable by root, not the web application. Only directories needed for application state and logs are writable by the PHP service user. This reduces the risk of a web application compromise modifying its own executable code.

12.4 Initialize SQLite

Fresh installation only:

ls -l /var/www/roundcube/SQL/sqlite.initial.sql
sudo -u www-data sqlite3 /var/lib/roundcube/roundcube.sqlite \
  < /var/www/roundcube/SQL/sqlite.initial.sql
sudo chmod 600 /var/lib/roundcube/roundcube.sqlite
sudo -u www-data sqlite3 /var/lib/roundcube/roundcube.sqlite '.tables'

Do not run the initial schema against a live database. SQLite creates its database and potentially journal/WAL files in the same directory, so the directory must be writable by www-data, not just the database file. A user can see only the preferences associated with their Roundcube account. The SQLite file still contains sensitive data and must not be served by HTTP.

12.5 Roundcube configuration

Generate a unique application encryption key privately. The original instructions used openssl rand -hex 12 to create a 24-character value. Keep the actual value when restoring an existing deployment; changing it can invalidate encrypted session data. Check the installed version's key requirements before generating a fresh key.

Create /var/www/roundcube/config/config.inc.php:

<?php
$config = [];

// SQLite application data (not the actual IMAP mailbox).
$config['db_dsnw'] = 'sqlite:////var/lib/roundcube/roundcube.sqlite?mode=0600';

// IMAP over implicit TLS, using loopback to avoid public-IP hairpinning.
$config['imap_host'] = 'ssl://127.0.0.1:993';
$config['imap_conn_options'] = [
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
        'allow_self_signed' => false,
        'peer_name' => 'mail.example.com',
    ],
];

// Authenticated SMTP over STARTTLS; reuse the logged-in IMAP credentials.
$config['smtp_host'] = 'tls://127.0.0.1:587';
$config['smtp_user'] = '%u';
$config['smtp_pass'] = '%p';
$config['smtp_conn_options'] = [
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
        'allow_self_signed' => false,
        'peer_name' => 'mail.example.com',
    ],
];

$config['product_name'] = 'reader Mail';
$config['skin'] = 'elastic';
$config['support_url'] = '';
$config['des_key'] = 'REPLACE_WITH_PRIVATE_24_CHARACTER_KEY';
$config['enable_installer'] = false;
$config['force_https'] = true;
$config['session_lifetime'] = 30;
$config['identities_level'] = 3;

$config['temp_dir'] = '/var/lib/roundcube/temp';
$config['log_dir'] = '/var/log/roundcube';
$config['log_driver'] = 'file';
$config['log_logins'] = true;
$config['log_session'] = false;

$config['drafts_mbox'] = 'Drafts';
$config['sent_mbox'] = 'Sent';
$config['junk_mbox'] = 'Junk';
$config['trash_mbox'] = 'Trash';
$config['default_folders'] = [
    'INBOX', 'Drafts', 'Sent', 'Junk', 'Trash', 'Archive',
];
$config['create_default_folders'] = true;
$config['plugins'] = ['archive', 'zipdownload'];
$config['language'] = 'en_US';

The original configuration intentionally connects to loopback while validating the server's certificate against its DNS name with peer_name. This avoids disabling certificate verification. %u and %p use the logged-in user's credentials to send mail on port 587. They are not DNSExit credentials. identities_level constrains user identities in the interface; it is not a substitute for MTA-side enforcement. force_https and a short session lifetime reduce exposure of credentials and long-lived sessions. Disable the installer in production.

sudo chown root:www-data /var/www/roundcube/config/config.inc.php
sudo chmod 640 /var/www/roundcube/config/config.inc.php
sudo php -l /var/www/roundcube/config/config.inc.php

12.6 Dedicated PHP-FPM pool

Verify the Caddy service account:

systemctl show caddy -p User -p Group

The build assumed the standard caddy service user. Create /etc/php/8.5/fpm/pool.d/roundcube.conf:

[roundcube]
user = www-data
group = www-data
listen = /run/php/roundcube.sock
listen.owner = caddy
listen.group = caddy
listen.mode = 0660
pm = ondemand
pm.max_children = 3
pm.process_idle_timeout = 15s
pm.max_requests = 300
request_terminate_timeout = 120s
php_admin_value[memory_limit] = 128M
php_admin_value[upload_max_filesize] = 15M
php_admin_value[post_max_size] = 20M
php_admin_flag[display_errors] = off
php_admin_flag[log_errors] = on

pm = ondemand creates workers when requests arrive instead of keeping a large idle pool. The child limit limits concurrency, not total memory: three workers may each use significant memory. The master and any other configured pools also consume RAM. The Unix socket's mode and owner grant Caddy access while PHP code runs as www-data. Disabling displayed errors avoids exposing internal paths and stack traces to users; errors are logged instead.

The PHP upload and POST limits are not the same as the final SMTP message size limit. MIME base64 encoding adds roughly one-third to a binary attachment, plus message headers. A Postfix or DNSExit message limit can therefore reject an attachment smaller than PHP's upload allowance. Inspect postconf message_size_limit and relay limits before changing them.

sudo php-fpm8.5 -t
sudo systemctl enable --now php8.5-fpm
sudo systemctl restart php8.5-fpm
sudo ls -l /run/php/roundcube.sock

12.7 Caddy configuration (confirmed from user-provided file)

The actual Caddyfile supplied by the owner contained both virtual hosts:

example.com, www.example.com {
    encode zstd gzip
    reverse_proxy 127.0.0.1:3000
}

mail.example.com {
    root * /var/www/roundcube/public_html

    @blocked path /installer.php /installer/* /config/* /temp/* /logs/* /SQL/* /bin/* /.*
    respond @blocked 404

    php_fastcgi unix//run/php/roundcube.sock
    file_server
    encode gzip zstd

    header {
        Strict-Transport-Security "max-age=31536000"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "SAMEORIGIN"
        Referrer-Policy "same-origin"
        -Server
    }
}

The root directive points only to the public web subtree. That is the main protection keeping application configuration and private database files outside the document root. The blocked paths provide defense in depth and disable installer access; /.* is a path matcher for root-level dot-prefixed paths, not a general guarantee against every nested hidden file. Do not rely on that matcher alone to protect secrets. Review symlinks and the public document root as well.

php_fastcgi passes PHP requests to PHP-FPM over the Unix socket; file_server serves static assets. Caddy selects the site by hostname and negotiates HTTPS automatically. HSTS instructs browsers that have successfully visited the site to prefer HTTPS for the configured duration; apply it only once TLS is healthy. The other headers limit MIME sniffing, framing and referrer leakage. They are useful browser defenses, not a complete application security policy.

sudo cp -a /etc/caddy/Caddyfile /root/Caddyfile.before-change
sudo caddy fmt --overwrite /etc/caddy/Caddyfile
sudo caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
sudo systemctl reload caddy
sudo journalctl -u caddy -n 50 --no-pager

The actual validation log reported Valid configuration. Its formatting warning was harmless; the shutdown messages referred to the validation process, not the production web server. Validation does not prove PHP execution, database access or public certificate issuance, so functional tests were also necessary.

curl -I https://example.com
curl -I https://mail.example.com
curl -I https://mail.example.com/installer.php
curl -I https://mail.example.com/config/config.inc.php
curl -I https://mail.example.com/.env

The latter three should not expose protected data. A denial (typically 404/403) is expected. A successful application response or appropriate redirect at the main webmail URL is expected; 502 usually means Caddy cannot communicate with PHP-FPM. The owner successfully logged in at https://mail.example.com and saw four existing messages, proving the basic PHP, SQLite, IMAP and HTTPS path.

12.8 Configure sender identity and verify mail

In Roundcube, open Settings -> Identities. Set the display name and the exact authenticated account address. Leave Reply-To and Bcc empty unless deliberately required. Send an email from the custom address to an external Gmail account; then reply from an independent Gmail account to the custom address. Check both the local Inbox and Gmail forwarding destination. Confirm Sent contains the outgoing copy.

Example professional signature:

Kind regards,
reader Afzal
Software Engineer
https://example.com

Roundcube is installed upstream rather than through a distribution package in this design. Operating system automatic updates will not necessarily update it. Subscribe to or periodically review its security releases; back up the application configuration and SQLite database, use the upstream upgrade procedure, and test login and both delivery directions after upgrades.

13. Fail2ban: brute-force protection

13.1 How Fail2ban works

Fail2ban monitors log files or the systemd journal for patterns indicating failed authentication. A filter identifies relevant lines and extracts the client address. A jail combines the filter with log source, time window, attempt count and ban action. The ban action inserts firewall rules blocking the offending IP for a period. It is reactive abuse mitigation, not a replacement for strong passwords, correct authorization, TLS, security patching or multi-factor authentication.

The installation used:

sudo apt install -y fail2ban python3-systemd
sudo systemctl enable --now fail2ban

13.2 IMAP and SMTP submission jails

The original proposed /etc/fail2ban/jail.d/mail.local was:

[dovecot]
enabled = true
port = 993
backend = systemd
banaction = iptables-multiport
maxretry = 5
findtime = 600
bantime = 3600
journalmatch = _SYSTEMD_UNIT=dovecot.service

[postfix-sasl]
enabled = true
port = 587
filter = postfix[mode=auth]
backend = systemd
banaction = iptables-multiport
maxretry = 5
findtime = 600
bantime = 3600
journalmatch = SYSLOG_IDENTIFIER=postfix/submission/smtpd

This is the intended configuration, not proof that the installed Fail2ban version interprets all settings identically. In particular, journalmatch may be supplied through the filter definition or systemd backend options depending on version. Check the effective journal match, installed filter and live authentication logs; if the jail fails to count a real bad login, correct that before considering the service protected. Do not set ignoreip to a broad public network. Keep loopback excluded from backend authentication bans so webmail cannot cause the mail server to ban its own local address.

sudo fail2ban-client -t
sudo systemctl restart fail2ban
sudo fail2ban-client status
sudo fail2ban-client status dovecot
sudo fail2ban-client status postfix-sasl
sudo fail2ban-client get dovecot journalmatch
sudo fail2ban-client get postfix-sasl journalmatch

Roundcube connects locally to the backend services, so a remote attacker attempting a webmail login will not necessarily be visible to the IMAP/SMTP jails by the true browser IP. A webmail-specific jail is necessary.

13.3 The Roundcube filter problem we actually solved

Roundcube was configured with file login logging in /var/log/roundcube/userlogins.log. The user first supplied a successful login and then deliberately generated one failed login. Redacted representations of those log formats are:

[30-Nov-2026 10:35:32 +0000]: <SESSION> Successful login for [email protected] (ID: 1) from CLIENT_IP (X-Forwarded-For: CLIENT_IP) in session SESSION_ID
[30-Nov-2026 11:08:46 +0000]: <SESSION> Failed login for [email protected] from CLIENT_IP (X-Forwarded-For: CLIENT_IP) in session SESSION_ID (error: 0)

The absence of errors.log was not a problem; the authentication event was present in userlogins.log. Testing the distribution's default filter yielded:

Prefregex: 2 total
Failregex: 0 total
Lines: 2 lines, 0 ignored, 0 matched, 2 missed

This proved the file was readable and timestamps were recognized, but the default filter did not recognize the newer failed-login format. We created a custom filter adapted to the actual line and the optional forwarded-for field.

Create /etc/fail2ban/filter.d/roundcube-custom.conf:

[Definition]
failregex = ^\s*(?:\[\])?\s*:\s*<[\w]+>\s+Failed login for \S+ from <ADDR>(?: \(X-Forwarded-For: [^()\r\n]*\))? in session \w+ \(error: \d+\)\s*$
ignoreregex =

The regex starts and ends at line boundaries, matches the failure phrase (not a successful login), captures the primary IP through Fail2ban's <ADDR> placeholder, allows the optional forwarded-for annotation, and matches the remaining session/error fields. Fail2ban removes the recognized timestamp before applying the regex; the optional empty brackets and colon account for that. The important principle is matching a trusted client-address field from the application log, not blindly extracting arbitrary user-controlled text.

sudo fail2ban-regex /var/log/roundcube/userlogins.log \
  /etc/fail2ban/filter.d/roundcube-custom.conf --print-all-matched

Expected for the two original lines: one matched (failure), one missed (success). The owner confirmed the fix worked. Retest against the current format when Roundcube is upgraded.

13.4 Activate the Roundcube jail

Create /etc/fail2ban/jail.d/roundcube.local:

[roundcube-auth]
enabled = true
filter = roundcube-custom
port = http,https
protocol = tcp
backend = polling
logpath = /var/log/roundcube/userlogins.log
banaction = iptables-multiport
maxretry = 5
findtime = 600
bantime = 3600
usedns = no

Five failures in ten minutes trigger a one-hour ban. Polling is appropriate for this small file-based jail. The ban is enforced on TCP ports 80 and 443 at the host. Because the mail hostname is DNS only, a direct browser normally connects from its own IP. Verify that Caddy and Roundcube only trust forwarded headers from trusted proxies; a forged header must not determine who gets banned. If you later place a proxy in front of webmail, an IP ban at the origin may block the proxy rather than the attacker unless the enforcement architecture is redesigned. Public QUIC/HTTP3 over UDP 443 would not be covered by this TCP-only jail; UDP 443 was not opened in our firewall design.

sudo fail2ban-client -t && sudo systemctl restart fail2ban
sudo fail2ban-client status roundcube-auth

A controlled test uses an address reserved for documentation rather than the administrator's actual IP:

sudo fail2ban-client set roundcube-auth banip 192.0.2.123
sudo iptables -L INPUT -n --line-numbers
sudo iptables -L f2b-roundcube-auth -n
sudo fail2ban-client set roundcube-auth unbanip 192.0.2.123

The chain must be traversed before the relevant ACCEPT rule. Some versions name chains differently; inspect the real output. This tests rule insertion/removal, not the log matching itself. To verify detection, record the Total failed counter, generate a single incorrect login from an incognito window and check that it increases. Do not intentionally trigger five failed logins from your only administrative network. The web ban also affects direct access to the shared website on TCP 80/443; SSH is not covered by this jail.

If a legitimate user is banned, log in via SSH and use:

sudo fail2ban-client set roundcube-auth unbanip CLIENT_IP

Replace the placeholder with the actual trusted IP. Do not disable all jails or loosen TLS to recover a password.

14. Certificate renewal

14.1 Two independent renewal mechanisms

Caddy automatically manages its HTTPS certificates and storage. Certbot independently manages the mail hostname certificate used by Postfix and Dovecot. Renewing the Certbot file does not guarantee a running daemon reloads it; that is why a deployment hook was configured.

Check certificate paths and renewal settings without revealing the API token:

sudo certbot certificates
sudo postconf smtpd_tls_cert_file smtpd_tls_key_file
sudo doveconf -n | grep -E 'cert_file|key_file'
sudo grep -E 'authenticator|dns_cloudflare' \
  /etc/letsencrypt/renewal/mail.example.com.conf
sudo ls -l /root/.secrets/cloudflare.ini

The recorded token path was /root/.secrets/cloudflare.ini, mode 600. Keep the token valid and restricted to the required zone. A changed token or deleted OAuth/API configuration can silently break future certificate renewal even if current TLS is working.

14.2 Deploy hook

Create /etc/letsencrypt/renewal-hooks/deploy/reload-mail.sh:

#!/bin/sh
set -eu
if [ "$RENEWED_LINEAGE" = "/etc/letsencrypt/live/mail.example.com" ]; then
    systemctl reload postfix
    systemctl reload dovecot
    logger -t mail-cert-renewal "Mail TLS certificate successfully reloaded"
fi
sudo chmod 755 /etc/letsencrypt/renewal-hooks/deploy/reload-mail.sh
sudo certbot renew --cert-name mail.example.com --dry-run --run-deploy-hooks
sudo journalctl -t mail-cert-renewal -n 10 --no-pager
sudo systemctl enable --now certbot.timer
sudo systemctl list-timers --all | grep certbot

The dry run tests ACME validation without replacing the production certificate. The --run-deploy-hooks option additionally executes deploy hooks against the current active certificate after a successful dry run. It can reload services, so run it deliberately. Verify the success message and the hook log. The timer was observed active in the user's diagnostics; a separate final dry-run result was not supplied, so retain this as an acceptance check.

14.3 Test the served certificates, not only files on disk

openssl s_client -starttls smtp -connect 127.0.0.1:587 \
  -servername mail.example.com -verify_hostname mail.example.com \
  -verify_return_error </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates
openssl s_client -connect 127.0.0.1:993 \
  -servername mail.example.com -verify_hostname mail.example.com \
  -verify_return_error </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates
openssl s_client -connect mail.example.com:443 \
  -servername mail.example.com -verify_hostname mail.example.com \
  -verify_return_error </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates

SMTP and IMAP should normally show the same Certbot certificate. Caddy may have a different expiration date. To inspect the verification result itself, run openssl s_client without the final openssl x509 pipe and inspect the return code and errors. Do not declare TLS secure merely because a certificate is printed. Also test directly from an external client after any certificate change.

15. Restic and Rclone: encrypted off-server backups

15.1 Backup design

Cloudflare's duplicate Gmail forwarding is not a real backup. It does not capture messages in Sent/Drafts, folder changes, contacts, identities, authentication configuration or server credentials. Oracle VM loss would destroy the primary copy if nothing is backed up outside that VM.

Restic snapshots files, encrypts repository contents client-side, deduplicates identical data chunks, and compresses data using repository format v2. Rclone provides access to remote storage using the Google Drive API. Restic uses Rclone as a backend, so no plaintext mailbox folder is uploaded to Drive. A snapshot records a recoverable tree of files at a particular backup time; it is not an unencrypted zip file or a full VM image.

The design uses a daily backup at 02:00 UTC in this example. Retention target: seven daily, four weekly and six monthly snapshots. Pruning was initially manual due to limited RAM. Google Drive storage is subject to the account's available quota, shared with other Google services. The server has write access to its repository, so an attacker compromising root could delete backups; this is not immutable storage. Keep occasional independent offline copies and recovery credentials.

15.2 Install backup tools

sudo apt install -y restic rclone sqlite3
restic version
rclone version
sqlite3 --version
sudo install -d -m 700 /etc/mail-backup

15.3 Create Google OAuth credentials

The initial attempt used an External OAuth app in Testing mode. The Google Auth Platform UI disabled Publish until Branding was complete. An external testing application's refresh tokens can expire after seven days for the requested Drive scope, making an unattended backup unreliable. The build then selected Google's Personal mode where available for the owner's own account, avoiding unnecessary public-app verification/publishing. Google's UI and product availability may change. Consult the current Rclone Drive documentation and Google Auth Platform; if Personal mode is not available, use a suitable supported OAuth configuration with durable authorization for your own application and comply with Google's policies.

The actual guided steps were:

  1. Open Google Cloud Console / Google Auth Platform using the account intended to store the backup.
  2. Create a new personal OAuth project if Personal mode is available (https://console.cloud.google.com/auth/overview/personal was the link used during the build). Create a Desktop app OAuth client. Do not select an AI-agent option for this backup tool.
  3. Enable the Google Drive API for that same project.
  4. Save the generated client ID and secret privately. If the OAuth app requires verification or consent setup, follow the provider's current instructions rather than trying to bypass them.
  5. Configure Rclone with the app credentials and the least-privilege drive.file scope.

The drive.file scope allows access to files/folders created by or explicitly authorized for that OAuth application, not all personal files. Reusing the same OAuth app during recovery is important: a new app with drive.file may not see the repository created by the original app. Securely retain the OAuth project identity, client credentials, Google account recovery options and the Restic password separately from Oracle. A token is not a permanent substitute for controlling the Google account.

15.4 Authorize the headless VM from the Mac

Start the configuration on Oracle:

sudo rclone --config /etc/mail-backup/rclone.conf config
Prompt Response
New remote n
Name gdrive
Storage type drive
Client ID / secret The private values from the Google project
Scope drive.file
Service account Empty
Advanced configuration n unless required
Use browser on this machine n (headless server)

At the config_token> prompt the VM displays an rclone authorize command. Leave that SSH terminal running. Open a local Mac terminal:

brew install rclone
rclone version

Run the exact authorization command printed by the server. It has a form like:

rclone authorize "drive" "GENERATED_CONFIGURATION"

The placeholder is not a literal command argument; the real encoded configuration can contain sensitive OAuth information. The local browser opens, the owner signs into Google and grants permission, and the local terminal returns an authorization token. Copy the full token between the delimiters and paste it into the waiting server config_token> prompt. Answer No to Shared Drive for a normal personal Google Drive, keep the remote and quit configuration.

sudo chmod 600 /etc/mail-backup/rclone.conf
sudo rclone --config /etc/mail-backup/rclone.conf listremotes
sudo rclone --config /etc/mail-backup/rclone.conf about gdrive:
sudo rclone --config /etc/mail-backup/rclone.conf mkdir gdrive:example-mail-backup
sudo rclone --config /etc/mail-backup/rclone.conf lsd gdrive:

The folder should be visible in the intended Google account. An empty listing of unrelated folders is normal with drive.file scope. Do not post the authorization command, returned JSON, refresh token or rclone.conf publicly. If exposed, revoke the affected grant and reauthorize/rotate credentials. The user's successful snapshots later proved remote connectivity was working.

15.5 Generate the repository password and wrapper

On a fresh setup generate the repository password only once:

sudo sh -c '
umask 077
if [ ! -e /etc/mail-backup/restic-password ]; then
    openssl rand -base64 48 > /etc/mail-backup/restic-password
fi
'

Store it securely outside the VM, for example in an independent password manager, before relying on the backup. The Restic password and Google access are separate requirements: without the password the encrypted repository cannot be decrypted; without Google access the repository cannot be downloaded. Do not generate a different password on a recovery machine expecting to open the existing repository. Do not copy the password into this document.

Create /usr/local/sbin/mail-restic:

#!/bin/sh
set -eu
export RESTIC_REPOSITORY="rclone:gdrive:example-mail-backup"
export RESTIC_PASSWORD_FILE="/etc/mail-backup/restic-password"
export RCLONE_CONFIG="/etc/mail-backup/rclone.conf"
export GOMAXPROCS=2
export GOGC=50
exec /usr/bin/restic "$@"
sudo chmod 700 /usr/local/sbin/mail-restic
sudo mail-restic init   # first-time initialization only
sudo mail-restic snapshots

GOMAXPROCS and GOGC reduce runtime resource demand heuristically; they are not a hard memory cap. The wrapper avoids repeating repository configuration in every command. For an existing repository, skip init and test snapshots. Do not edit Drive's repository files directly. Restic manages directories such as data, index, keys, locks, snapshots and the repository config file.

15.6 Final backup script (with syntax fix)

SQLite's online .backup command makes a consistent copy of the live Roundcube database. Copying only a database file while SQLite is actively writing can omit committed state in a WAL or produce a problematic copy. The backup script stages a consistent database copy, runs an integrity check, captures virtual UID/GID and installed package records, then encrypts and uploads files.

The final script is reconstructed from the user's successful version after adding Rspamd and maintenance configuration. The optional mail-add-user path is included for the proposed multi-account extension. Add the helper to the backup only when it exists. All paths use ASCII spaces and ordinary Bash syntax.

Create /usr/local/sbin/mail-backup:

#!/bin/bash
set -euo pipefail
umask 077

exec 9>/run/lock/mail-backup.lock
flock -n 9 || exit 1

STAGE="/var/backups/mail-server"
install -d -m 700 "$STAGE"
trap 'rm -f "$STAGE/roundcube.sqlite"' EXIT

echo "Creating Roundcube database backup..."
rm -f "$STAGE/roundcube.sqlite"
sqlite3 /var/lib/roundcube/roundcube.sqlite \
    ".timeout 10000" \
    ".backup '$STAGE/roundcube.sqlite'"

if [ "$(sqlite3 "$STAGE/roundcube.sqlite" 'PRAGMA integrity_check;')" != "ok" ]; then
    echo "SQLite integrity check failed."
    exit 1
fi

getent passwd vmail > "$STAGE/vmail-user.txt"
getent group vmail > "$STAGE/vmail-group.txt"
dpkg-query -W > "$STAGE/packages.txt"

PATHS=(
    /var/vmail
    /etc/postfix
    /etc/dovecot
    /etc/letsencrypt
    /etc/caddy
    /etc/fail2ban
    /etc/php/8.5/fpm
    /var/www/roundcube/config
    /var/www/roundcube/plugins
    /root/.secrets/cloudflare.ini
    /var/backups/mail-server
    /etc/rspamd
    /var/lib/rspamd
)

for OPTIONAL in \
    /etc/iptables \
    /etc/hosts \
    /etc/logrotate.d \
    /usr/local/sbin/mail-backup \
    /usr/local/sbin/mail-restic \
    /etc/systemd/system/mail-backup.service \
    /etc/systemd/system/mail-backup.timer \
    /etc/systemd/journald.conf.d \
    /usr/local/sbin/mail-health \
    /etc/systemd/system/mail-health.service \
    /etc/systemd/system/mail-health.timer \
    /usr/local/sbin/mail-add-user
do
    if [ -e "$OPTIONAL" ]; then
        PATHS+=("$OPTIONAL")
    fi
done

echo "Starting encrypted backup..."
/usr/local/sbin/mail-restic backup \
    --compression auto \
    --tag mail-server \
    --exclude '/var/vmail/*/Maildir/tmp' \
    "${PATHS[@]}"
echo "Mail server backup completed successfully."
sudo chmod 700 /usr/local/sbin/mail-backup
sudo bash -n /usr/local/sbin/mail-backup && echo 'Syntax OK'
sudo mail-backup
sudo mail-restic snapshots
sudo mail-restic check

Technical details:

  • set -euo pipefail makes many failed commands, unset variables and failed pipeline components fail the backup instead of silently proceeding. It is not a guarantee of transactional behavior.
  • umask 077 creates new sensitive files with restrictive defaults. The staging directory is root-only.
  • flock prevents simultaneous runs of this backup script using a local lock file. Restic also has repository locks, useful when backup and maintenance commands run concurrently.
  • The trap removes the temporary SQLite backup after the script exits. The encrypted remote snapshot retains the copy.
  • PATHS is a Bash array, and "${PATHS[@]}" passes every path as its own argument even if spaces are present.
  • The explicit paths include all mailboxes, Dovecot password databases, Postfix relay credentials, TLS keys and Cloudflare DNS token. They are sensitive even though stored encrypted remotely.
  • The script deliberately excludes the Restic password and Rclone credential file from its normal snapshot. Keep those in separate secure recovery storage; a repository cannot be the only place containing its own unlock credentials.
  • The tmp Maildir directory exclusion avoids incomplete deliveries. Other live Maildir files can be renamed or moved during a scan, so the backup is not an atomic filesystem snapshot. Inspect exit status and warnings and retry a failed backup. Folder state can change while a backup runs.

The syntax error we encountered: after adding maintenance paths, the line /etc/systemd/system/mail-backup.timer had no continuation backslash. Bash interpreted the following /etc/systemd/journald.conf.d as an unexpected token because it had ended the for ... in word list. We corrected the backslash after every intermediate path and removed it from the final path before do. A backslash must be immediately followed by the newline, not by spaces or rich-text formatting. bash -n validates syntax without executing the script. It does not validate file existence, credentials, backup consistency or connectivity; those require an actual run.

An alternative future refactor is to use a second Bash array for optional paths and iterate for OPTIONAL in "${OPTIONAL_PATHS[@]}"; do ...; done, eliminating long backslash continuations. This was not required to fix the live script.

15.7 Schedule the backup with systemd

Create /etc/systemd/system/mail-backup.service:

[Unit]
Description=Encrypted Mail Server Backup
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
User=root
UMask=0077
ExecStart=/usr/local/sbin/mail-backup
Nice=10
IOSchedulingClass=idle

Create /etc/systemd/system/mail-backup.timer:

[Unit]
Description=Daily Mail Server Backup

[Timer]
OnCalendar=*-*-* 02:00:00 UTC
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now mail-backup.timer
sudo systemctl list-timers --all | grep mail-backup
sudo systemctl start mail-backup.service
sudo journalctl -u mail-backup.service -n 50 --no-pager

A oneshot service runs and exits; no backup daemon consumes RAM between scheduled runs. Persistent=true can catch up a missed calendar run when the timer becomes active. Nice=10 and idle I/O scheduling are best-effort scheduling hints. They are not guaranteed CPU or I/O resource limits. Check the next scheduled run with systemctl and verify the first unattended run separately from any manual snapshot.

15.8 Verify a backup run

After creating a snapshot, inspect the latest snapshot and confirm it includes mail, consistent webmail data and the current service configuration. Create a fresh snapshot after account additions or major configuration changes. Its logical size can differ from the storage consumed after deduplication and compression.

sudo mail-restic snapshots --latest 1
sudo mail-restic stats
sudo mail-restic check
sudo systemctl show mail-backup.service -p Result -p ExecMainStatus
sudo journalctl -u mail-backup.service --since '2 days ago' --no-pager

check validates repository consistency, but a default check does not read all backed-up data packs. A periodic check --read-data or a supported subset check (see installed version's help) verifies stored data more thoroughly and consumes additional bandwidth. Repository integrity checks and restore drills serve different purposes.

15.9 Test restoration safely

Choose a new, private temporary directory. Never use / as a trial restore target. Inspect the repository first. The example uses latest; for a reproducible drill, replace it with an explicit verified snapshot ID.

sudo install -d -m 700 /root/mail-restore-test
sudo mail-restic restore latest --tag mail-server \
  --target /root/mail-restore-test
sudo du -sh /root/mail-restore-test/var/vmail
sudo sqlite3 /root/mail-restore-test/var/backups/mail-server/roundcube.sqlite \
  'PRAGMA integrity_check;'

Expected SQLite result: ok. Inspect restored Maildir files, directory ownership, configuration presence and a sample message. The restored copy includes secrets; protect it and delete the temporary copy when finished (verify the exact path first):

sudo rm -rf -- /root/mail-restore-test

Perform this drill before relying on the repository for disaster recovery. A production restore is a separate procedure described in Section 23.

15.10 Retention and pruning

Preview before deleting snapshots:

sudo mail-restic forget --tag mail-server \
  --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --dry-run

Restic's default grouping includes snapshot paths (in addition to host/tags as applicable); because our backup path list evolved, older and newer path groups can be retained separately. Review the grouping and dry-run carefully. If intentionally treating all snapshots of this host and tag as one series, use the installed version's --group-by host,tags option with a dry run first, understanding that older incomplete snapshots may have different contents.

When the policy is correct, and only after verifying recovery access, apply the intended policy:

sudo mail-restic forget --tag mail-server \
  --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune
sudo mail-restic check

forget deletes snapshot references; prune removes no-longer-referenced stored data. These are destructive maintenance operations. Do not run during an active backup or automatically after a failed backup. Keep pruning manual initially to avoid competing with mail delivery on the 1 GB VM. Restic's repository locking protects many operations but is not a reason to schedule maintenance at the same time as backups. Consider a monthly maintenance window after observing resources and ensuring off-server recovery copies.


16. Rspamd: spam filtering

16.1 Why add filtering after Cloudflare?

Cloudflare already evaluates incoming mail, and Gmail independently filters its forwarded copy. The local Oracle mailbox should still have its own filtering policy. Rspamd is an event-driven spam filter: it evaluates authentication, message structure, content, URL/domain reputation, DNS blocklists and other rules. Each rule can contribute a positive or negative score. The total, together with explicit policy actions, determines how the message should be handled. It does not deliver mail by itself.

We deliberately did not install ClamAV, Redis, or other large ancillary services. Rspamd can perform stateless scanning without Redis, but its Bayesian learning and several other features depend on Redis. Rspamd is not an antivirus replacement, and no malware-scanning guarantee is provided by this configuration.

The initial policy marks spam instead of rejecting or deleting it. On a personal academic/professional account, losing an important legitimate email can be worse than temporarily storing a spam message. Forwarding-aware authentication results also needed to be tested before enabling automatic sorting.

16.2 Install the filter

The upstream Rspamd stable repository was selected for Ubuntu 26.04 rather than relying on an older package. Repository support, package versions and signing keys can change. Check the official installation instructions, apt-cache policy rspamd, and the current supported release before installing on a fresh host. The original installation sequence was:

sudo apt update
sudo apt install -y curl gpg lsb-release ca-certificates
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://rspamd.com/apt-stable/gpg.key \
  | gpg --dearmor \
  | sudo tee /etc/apt/keyrings/rspamd.gpg >/dev/null
sudo chmod 644 /etc/apt/keyrings/rspamd.gpg

Verify the key fingerprint against the current upstream instructions before trusting the repository. A signing key is a trust decision, not just a download step.

echo "deb [signed-by=/etc/apt/keyrings/rspamd.gpg] https://rspamd.com/apt-stable/ $(lsb_release -cs) main" \
  | sudo tee /etc/apt/sources.list.d/rspamd.list
sudo apt update
apt-cache policy rspamd
sudo apt install -y --no-install-recommends rspamd
rspamd --version

Do not add an unsupported distribution codename or install an untrusted package to work around an apt error. Use a supported official package and inspect the current release notes.

16.3 Worker configuration and local-only sockets

Rspamd uses different workers for message scanning and control. The selected design uses the proxy worker in self-scan mode to avoid a separate normal scanner. The controller provides management and statistics, and in the recorded build it accepted the local rspamc test.

Back up initial settings and create local overrides:

sudo cp -a /etc/rspamd /root/rspamd-original
sudo mkdir -p /etc/rspamd/local.d

/etc/rspamd/local.d/worker-proxy.inc:

bind_socket = "127.0.0.1:11332";
count = 1;
milter = true;
upstream "local" {
    self_scan = true;
}

/etc/rspamd/local.d/worker-normal.inc:

enabled = false;

/etc/rspamd/local.d/worker-controller.inc:

bind_socket = "127.0.0.1:11334";
count = 1;

The local.d convention overrides packaged defaults without editing every upstream configuration file. This makes upgrades easier but requires checking the effective merged configuration. Some packages include additional worker definitions; validate the installed version rather than assuming a directive always disables a worker. Only loopback should listen on 11332 and 11334, and 11333 should be disabled in the selected layout. Do not expose these ports through the OCI firewall or Caddy.

16.4 Conservative spam actions

/etc/rspamd/local.d/actions.conf:

reject = null;
greylist = null;
add_header = 6;

/etc/rspamd/local.d/greylist.conf:

enabled = false;

The score threshold of 6 assigns the add header action. Disabling a score threshold does not necessarily disable modules that force actions independently, so inspect effective rules and scan results. Disabling the greylist module avoids unnecessary delivery delays. The platform initially permits normal and marked mail; the later Sieve rule sorts marked messages into Junk.

/etc/rspamd/local.d/milter_headers.conf:

extended_spam_headers = true;
skip_local = false;
skip_authenticated = false;

These options expose local scan diagnostics on the incoming messages. Since the Milter is attached only to the incoming service, we do not deliberately add internal Rspamd results to outgoing mail. The headers used during testing were X-Spamd-Result, X-Rspamd-Action, X-Rspamd-Queue-Id and X-Rspamd-Server. The score header shows the symbols and their contributions. X-Rspamd-Action is the classification used by Sieve. Do not base delivery policy on a forged externally supplied copy of this header; Section 17 addresses it.

sudo rspamadm configtest
sudo rspamadm configdump actions
sudo systemctl enable --now rspamd
sudo systemctl restart rspamd
sudo systemctl is-active rspamd
sudo ss -lntp | grep -E '11332|11333|11334'
free -h
sudo systemctl show rspamd -p MemoryCurrent

Read the entire configtest output, including warnings; syntax OK alone does not prove every setting has been recognized.

16.5 Independent synthetic scanner test

Create a harmless test message:

cat > /tmp/rspamd-test.eml <<'EOF'
From: [email protected]
To: [email protected]
Subject: Rspamd Test
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8

Hello,

This is a normal test message to verify that the
Rspamd email scanning service is functioning.

Kind regards
EOF
rspamc -h 127.0.0.1:11334 /tmp/rspamd-test.eml

The actual result was:

Results for file: /tmp/rspamd-test.eml (0.519 seconds)
Action: add header
Spam: true
Score: 8.00 / 6.00
Observed symbol Score
HFILTER_HOSTNAME_UNKNOWN +2.50
MISSING_MID +2.50
DMARC_POLICY_REJECT +2.00
MISSING_DATE +1.00
ONCE_RECEIVED +0.10
MIME_GOOD -0.10
Total 8.00

The synthetic message lacked real transport metadata, a Message-ID, a Date and valid sender authentication. It was expected to look suspicious. It proved the scanner could process an email and assign the configured action; it did not justify raising the spam threshold. Synthetic tests can produce different scores if DNS or rule sets change.

16.6 Integrate only incoming Postfix service

The Milter interface enables Postfix to consult Rspamd during incoming SMTP delivery and receive header modifications and actions. We only attached it to the smtp/inet listener on port 25, leaving authenticated port 587 submissions and DNSExit behavior unchanged.

sudo cp -a /etc/postfix/master.cf /etc/postfix/master.cf.before-rspamd
sudo postconf smtpd_milters non_smtpd_milters
sudo postconf -P | grep -i milter

Assuming no preexisting Milter must be preserved:

sudo postconf -P \
  'smtp/inet/smtpd_milters=inet:127.0.0.1:11332' \
  'smtp/inet/milter_default_action=accept' \
  'smtp/inet/milter_protocol=6'
sudo postfix check && sudo systemctl reload postfix
sudo postconf -P | grep -i milter

milter_default_action=accept is a fail-open policy: if the filter is unavailable or times out under applicable failure conditions, Postfix can continue accepting mail rather than making the mailbox unavailable. It is a reliability choice, not a claim that explicit Rspamd rejections are ignored. Unscanned mail must not be treated as proven legitimate, and externally supplied classification headers must be stripped so that a failed scan does not trust a forgery.

Test a new external email and use Roundcube's More -> Show source to inspect the Rspamd headers. The live incoming test is analyzed in Section 18. To diagnose missing scanning:

sudo rspamc -h 127.0.0.1:11334 stat
sudo tail -n 50 /var/log/rspamd/rspamd.log
sudo journalctl -u rspamd -n 50 --no-pager
sudo journalctl --since '10 minutes ago' | grep -i milter

The application log typically contains individual scans; the journal may contain mainly startup and service messages.

16.7 Access the Rspamd dashboard safely from macOS

This example uses a local SSH key at ~/.ssh/example-mail-key. On the Mac, outside the VM's existing SSH session:

chmod 600 ~/.ssh/example-mail-key
ssh -i ~/.ssh/example-mail-key \
  -N \
  -L 127.0.0.1:11334:127.0.0.1:11334 \
  -o ExitOnForwardFailure=yes \
  [email protected]

The -N flag requests no remote shell command; -L binds a local Mac TCP socket on 127.0.0.1 and forwards traffic through the encrypted SSH connection to the VM's loopback controller. ExitOnForwardFailure prevents a misleading running tunnel if local binding fails. The terminal staying open with no prompt is expected. Open http://127.0.0.1:11334 in a local browser. Press Ctrl+C in that terminal to close the tunnel without stopping Rspamd.

The controller may trust local connections or require a password depending on installed configuration. Keep it private and configure appropriate controller authentication for anyone with shell access or tunnels. SSH tunneling is not a reason to publish 11334 on the Internet. If local port 11334 is occupied, map another local port (e.g. 11335) to remote 11334 and browse the matching local URL.

16.8 Back up and rollback the filter

/etc/rspamd and /var/lib/rspamd were added to the Restic script. The third observed snapshot included both. The upstream apt source/key are not automatically included by the original path list; keep a copy of the repository instructions and optionally extend the backup to capture the specific source/key files. Do not restore expired package signing trust blindly.

If Rspamd disrupts delivery, remove only our service-level overrides, assuming there were none before this integration:

sudo postconf -PX \
  'smtp/inet/smtpd_milters' \
  'smtp/inet/milter_default_action' \
  'smtp/inet/milter_protocol'
sudo postfix check && sudo systemctl reload postfix
sudo systemctl disable --now rspamd

If previous Milter overrides existed, restore those instead of removing them. Rollback does not delete stored messages. Under the Sieve rule in Section 17, mail lacking the locally generated action goes to INBOX, provided the ingress header-stripping policy is effective.

17. Dovecot LMTP and Sieve: automatic Junk sorting

17.1 Why the delivery agent changed

Before this phase Postfix's virtual transport placed messages directly into Maildir. It could not run Dovecot's Sieve rules as part of that delivery. We retained the existing Maildir storage and changed the final delivery agent to Dovecot LMTP (Local Mail Transfer Protocol). LMTP is similar to SMTP but designed for local delivery with per-recipient results. Postfix connects to Dovecot through a protected Unix socket instead of a new public port. Dovecot can then run Sieve, update mailbox state and report the delivery result to Postfix.

This is an architectural change to the final delivery step, not a migration of existing messages into a new storage format. We tested it directly before changing Postfix's production transport.

17.2 Back up and install packages

sudo install -d -m 700 /root/before-lmtp
sudo cp -a /etc/dovecot /root/before-lmtp/
sudo cp -a /etc/postfix /root/before-lmtp/
sudo postconf virtual_transport virtual_mailbox_domains virtual_mailbox_maps
sudo apt install -y --no-install-recommends dovecot-lmtpd dovecot-sieve
dovecot --version
command -v sievec
command -v sieve-test

The user subsequently provided a Dovecot startup log for version 2.4.2 and imap, lmtp. We did not enable ManageSieve, which would allow users to edit filtering scripts remotely. A server-wide spam rule suffices for the present design.

17.3 Separate mailbox lookup from authentication

Incoming SMTP arrives with an internal recipient such as [email protected]; IMAP and SMTP submission authenticate as [email protected]. Dovecot LMTP must resolve the internal recipient to the same home. Adding both addresses to a password database would also risk creating an unintended alternative login. Instead use a separate user database with no password hashes.

The original one-time migration command built /etc/dovecot/mailbox-users from the existing reader password record, stripping the password field:

sudo awk -F: '
BEGIN { OFS=":" }
$1 == "[email protected]" {
    $2=""
    print
    $1="[email protected]"
    print
}
' /etc/dovecot/virtual-users \
  | sudo tee /etc/dovecot/mailbox-users >/dev/null
sudo chown root:dovecot /etc/dovecot/mailbox-users
sudo chmod 640 /etc/dovecot/mailbox-users

Do not rerun that migration command on a multi-account server: it overwrites the destination database with only the reader records. Add new accounts using Section 20 instead. The single-account database now contains:

[email protected]::5000:5000::/var/vmail/reader::
[email protected]::5000:5000::/var/vmail/reader::

The UID/GID values are illustrative values; use the IDs assigned to your service account. The public login remains in virtual-users with its hash; both address forms exist in mailbox-users with the same home. This separation is why the later account script must update both files.

17.4 Final Dovecot configuration

Edit the existing /etc/dovecot/dovecot.conf, retaining all working TLS, IMAP, auth-socket and namespace settings. Replace protocols = imap with protocols = imap lmtp. Point only the userdb at /etc/dovecot/mailbox-users. Leave passdb pointing to /etc/dovecot/virtual-users.

For clarity, this is the consolidated Dovecot 2.4 configuration reconstructed from the recorded phases. Compare with doveconf -n rather than overwriting additional settings that may exist on the live machine.

dovecot_config_version = 2.4.0
dovecot_storage_version = 2.4.0
protocols = imap lmtp
listen = 0.0.0.0

mail_driver = maildir
mail_path = ~/Maildir
first_valid_uid = 5000
last_valid_uid = 5000

auth_mechanisms = plain login
auth_allow_cleartext = no
auth_verbose = yes

passdb passwd-file {
    passwd_file_path = /etc/dovecot/virtual-users
}
userdb passwd-file {
    passwd_file_path = /etc/dovecot/mailbox-users
}

ssl = required
ssl_min_protocol = TLSv1.2
ssl_server_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_server_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem

service imap-login {
    inet_listener imap {
        port = 0
    }
    inet_listener imaps {
        port = 993
        ssl = yes
    }
}

service auth {
    unix_listener /var/spool/postfix/private/auth {
        mode = 0660
        user = postfix
        group = postfix
    }
}

namespace inbox {
    inbox = yes
    separator = /
    mailbox Drafts {
        auto = subscribe
        special_use = \Drafts
    }
    mailbox Sent {
        auto = subscribe
        special_use = \Sent
    }
    mailbox Junk {
        auto = subscribe
        special_use = \Junk
    }
    mailbox Trash {
        auto = subscribe
        special_use = \Trash
    }
    mailbox Archive {
        auto = subscribe
        special_use = \Archive
    }
}

service lmtp {
    unix_listener lmtp {
        mode = 0
    }
    unix_listener /var/spool/postfix/private/dovecot-lmtp {
        mode = 0600
        user = postfix
        group = postfix
    }
}

protocol lmtp {
    postmaster_address = [email protected]
    mail_plugins {
        sieve = yes
    }
}

sieve_script spam_filter {
    type = before
    path = /etc/dovecot/sieve/spam-filter.sieve
}

The named script's type = before makes it a server-wide script that runs before a user's personal filtering script, if any. protocol lmtp enables the Sieve delivery plugin on the delivery path instead of every IMAP process. The socket under Postfix's private spool allows Postfix to connect even if its delivery service uses the spool-relative socket name. The default standalone LMTP listener is disabled in the example. If the original configuration uses distribution includes, preserve equivalent settings without duplicating conflicting blocks.

17.5 Sieve rule and anti-forgery boundary

Create a root-managed Sieve directory and script:

sudo install -d -m 755 /etc/dovecot/sieve
sudo tee /etc/dovecot/sieve/spam-filter.sieve >/dev/null <<'EOF'
require ["fileinto"];

if header :is "X-Rspamd-Action" "add header" {
    fileinto "Junk";
    stop;
}
EOF
sudo sievec /etc/dovecot/sieve/spam-filter.sieve
sudo chmod 644 /etc/dovecot/sieve/spam-filter.sieve /etc/dovecot/sieve/spam-filter.svbin

require enables the fileinto extension. The header :is test compares the action value, fileinto stores the message in Junk, and stop ends script processing. Otherwise the normal implicit keep delivers to INBOX. No discard or automatic purge is configured. A different action such as rewrite subject is not matched by this specific script; review Sieve when changing the Rspamd policy.

Security boundary: an external sender can include a header named X-Rspamd-Action. Before trusting it, remove untrusted incoming copies and verify that the scanner-generated header is retained. The build added a Postfix header_checks rule, distinct from milter_header_checks, which concerns headers added by a Milter. Rspamd's standard x-rspamd-action routine also replaces preexisting copies by default in the documented configuration. The Postfix input sanitation is particularly useful when the filter fails open and does not add a new header.

Check existing header policies before changing them:

sudo postconf header_checks milter_header_checks

If there was no previous header_checks map, the recorded configuration was:

sudo tee /etc/postfix/spam-header-checks >/dev/null <<'EOF'
/^X-Rspamd-Action:/ IGNORE
EOF
sudo postmap -q 'X-Rspamd-Action: add header' regexp:/etc/postfix/spam-header-checks
sudo postconf -e 'header_checks = regexp:/etc/postfix/spam-header-checks'

A regex table is read as text; unlike a hash map it does not need compilation. postmap -q here tests the rule. Do not replace an existing header-checking policy without merging and testing it. Postfix has different stages for original headers and Milter modifications, so a standalone postmap -q is not a proof of end-to-end sanitation. milter_header_checks must not accidentally remove the legitimate locally generated header. Check the effective Rspamd milter_headers config and perform a controlled forged-header test through port 25, with the scanner running and, during a planned maintenance window if appropriate, with it unavailable. The message should not be sorted into Junk solely because of a forged header. A missing locally generated classification should normally fall back to INBOX. Include a forged-header integration test in your deployment checks.

The direct LMTP test in the next step intentionally bypasses Postfix so it can supply a simulated scanner header. The socket is not publicly accessible; external senders must not be able to take that route.

17.6 Validate user lookups and direct LMTP

sudo doveconf -n >/dev/null && echo 'Configuration valid'
sudo systemctl restart dovecot
sudo systemctl is-active dovecot
sudo ls -l /var/spool/postfix/private/dovecot-lmtp
sudo doveadm user [email protected]
sudo doveadm user -x service=lmtp [email protected]
sudo doveadm mailbox list -u [email protected]

Both lookup variants must resolve to the same UID/GID and /var/vmail/reader. Log into Roundcube again to confirm existing IMAP access. Do not switch Postfix if either lookup fails or if the Sieve script does not compile.

Controlled normal-message test:

sudo swaks --socket /var/spool/postfix/private/dovecot-lmtp \
  --protocol LMTP --from [email protected] \
  --to [email protected] \
  --header 'Subject: LMTP Inbox Test' \
  --header 'X-Rspamd-Action: no action' \
  --body 'This message should appear in Inbox.'

Controlled spam-classification test:

sudo swaks --socket /var/spool/postfix/private/dovecot-lmtp \
  --protocol LMTP --from [email protected] \
  --to [email protected] \
  --header 'Subject: LMTP Junk Test' \
  --header 'X-Rspamd-Action: add header' \
  --body 'This message should appear in Junk.'

The successful local delivery tests showed these results:

sieve: msgid=<...>: stored mail into mailbox 'INBOX'
sieve: msgid=<...>: fileinto action: stored mail into mailbox 'Junk'

This is direct evidence that the LMTP socket, internal user lookup and Sieve rule work. The tests do not depend on an actual spam email being sent across the Internet, which would introduce unnecessary uncertainty.

17.7 Switch Postfix's production transport

Only after the local tests pass:

sudo postconf -e 'virtual_transport = lmtp:unix:private/dovecot-lmtp'
sudo postfix check && sudo systemctl reload postfix
sudo postconf virtual_transport
sudo postqueue -p

virtual_mailbox_maps still controls known recipients at SMTP time. LMTP uses Dovecot's userdb for final placement. The public domain remains at Cloudflare; this is not an MX or DNS change. The user's log showed the transport change command and an empty queue. A later message confirmed operational receiving, but an exact external postfix/lmtp status=sent log was not retained. For the final acceptance test, send a fresh real message to the public address and confirm the same queue ID and local LMTP delivery in the logs:

sudo journalctl --since '10 minutes ago' \
  | grep -E 'postfix/lmtp|dovecot.*lmtp|sieve'
sudo postqueue -p
sudo doveadm mailbox status -u [email protected] 'messages unseen' INBOX Junk

The Gmail forwarding branch does not pass through this Dovecot Sieve filter; Gmail independently decides its own spam folder. Folder positions between Gmail and the Oracle mailbox need not match.

17.8 Rollback if delivery is broken

If the new transport fails, temporarily revert to the previous Postfix delivery method, provided the original virtual map paths and UID/GID are still intact:

sudo postconf -e 'virtual_transport = virtual'
sudo postfix check && sudo systemctl reload postfix
sudo postqueue -p

If necessary, restore the previously saved Dovecot configuration after checking that it is appropriate for the current number of mailboxes:

sudo cp -a /root/before-lmtp/dovecot/dovecot.conf /etc/dovecot/dovecot.conf
sudo systemctl restart dovecot

For a later multi-account deployment, an old single-account Dovecot snapshot may lack newer authentication/userdb configuration. Do not blindly restore it over a changed deployment. Keep recent backups and understand which phase is being rolled back. Do not delete the mail queue or Maildir to resolve a transport problem.

18. Email authentication and delivery checks

18.1 Verify incoming mail and forwarding

Send from an independent mail provider to the public mailbox; give the message a distinctive test subject. Find it in the local inbox and at each configured forwarding destination. Compare the SMTP trace and local scanner action. A normal message should be accepted locally and should not land in Junk solely because it was forwarded.

For forwarded mail, compare the original From domain with the envelope domain after forwarding. SPF applies to the envelope identity on the hop being checked. An aligned DKIM signature can still establish DMARC even when the envelope has been rewritten. ARC records authentication evidence across intermediaries. Use the receiving provider’s authentication results and the local Rspamd report together.

18.2 Verify outgoing relay authentication

Send from the webmail identity to an independent inbox. Look at the received message’s source and compare the Postfix queue logs with the relay’s delivery result. In the original build the outgoing test passed SPF, DKIM and DMARC. The sanitized example below shows what to check.

dkim=pass header.d=example.com header.s=relay
spf=pass [email protected]
dmarc=pass header.from=example.com

Check that the signing domain and envelope identity align with the visible From domain as intended. Use the relay’s published SPF instructions, since one observed relay IP may not cover its sending pool. A forwarded inbound copy is a separate test and cannot demonstrate outgoing authentication.

18.3 DMARC policy progression

The domain was left at monitoring policy. p=none tells receivers not to apply a requested quarantine/reject disposition just because DMARC fails; receivers can still apply their own spam policy. It does not actively reject spoofed mail, although alignment already passes for our legitimate test.

An optional monitoring record, if the address is ready to receive aggregate reports:

v=DMARC1; p=none; rua=mailto:[email protected]; adkim=r; aspf=r

Aggregate reports can be XML attachments and may be better routed to a separate dedicated address. This reporting addition was proposed, not confirmed. Only publish one DMARC record for the domain. After collecting a representative set of authentication reports and identifying all legitimate sending services, gradually move to p=quarantine and then p=reject if appropriate. Test the effect on legitimate forwarded mail, subdomains and any third-party services first. Policy changes affect the entire sending domain, not just one mailbox. No enforcement change is required merely because the initial outgoing test succeeded.

18.4 What authentication cannot solve

Passing SPF, DKIM and DMARC helps deliverability and reduces spoofing risk, but recipient systems also evaluate shared-relay reputation, message content, recipient engagement, complaints and volume. A legitimate message can still go to Junk. Do not use repeated messages to inflate sender activity or try to evade spam controls. Use normal correspondence, verify recipient addresses, and monitor genuine errors. Also, transport encryption is not end-to-end message encryption: Cloudflare, DNSExit, the VM and Gmail may process or store message content as part of delivery.


19. Maintenance, monitoring, and resource usage

19.1 Check service health and capacity

Check service health, listening sockets, memory pressure, disk space, and queued mail after installation and under normal use. Watch available memory and swap activity together; allocated swap by itself does not indicate current pressure. Disk monitoring should include Maildir, logs, and any backup staging directory.

sudo systemctl is-active caddy postfix dovecot rspamd fail2ban
sudo ss -ltn
free -h
vmstat 1 5
df -h
sudo postqueue -p

A running service can still have a broken listener or authentication path. Retain external functional checks for inbound delivery, submission, IMAPS and webmail.

19.2 Roundcube log rotation

The OS already had /etc/logrotate.d/ entries for Fail2ban, Rspamd, PHP-FPM, Certbot, rsyslog and other system components. Its logrotate.timer was active. Roundcube was installed upstream, so we added its missing log-rotation configuration.

Create /etc/logrotate.d/roundcube:

/var/log/roundcube/*.log {
    daily
    rotate 30
    maxsize 10M
    missingok
    notifempty
    compress
    delaycompress
    su www-data www-data
    create 0640 www-data www-data
}

This evaluates rotation daily, retains up to 30 rotated generations, compresses old logs and creates the new file with permissions accessible to the application. maxsize is evaluated when logrotate actually runs; it is not a real-time hard cap. A new file owner/mode must agree with the directory ownership. Fail2ban should follow the newly created log after rotation.

sudo logrotate -d /etc/logrotate.d/roundcube
# Controlled real rotation test; optional on an already-tested system:
sudo logrotate -f /etc/logrotate.d/roundcube
sudo ls -lah /var/log/roundcube/
sudo systemctl status logrotate.timer --no-pager

After rotation, generate a single failed webmail login and verify the new userlogins.log receives the event and the roundcube-auth jail counts it. Do not force repeated rotations of production logs just to make the command succeed. Log retention must balance storage and security investigation needs; logs can contain private addresses and metadata.

19.3 Limit journald growth

Create /etc/systemd/journald.conf.d/storage-limits.conf:

[Journal]
SystemMaxUse=300M
SystemKeepFree=5G
SystemMaxFileSize=32M
MaxRetentionSec=30day
sudo systemctl restart systemd-journald
sudo journalctl --disk-usage

These settings apply to the persistent system journal and provide limits/retention targets, not a guarantee that exactly 5 GiB will always be reserved against all other disk users. Active files and other processes can affect actual usage. The purpose is to avoid journal growth becoming the main consumer of a small disk.

19.4 Lightweight health-check script

The build deliberately avoided Grafana, Prometheus, Netdata or another always-running dashboard. A simple shell script can check the essential services, memory, disk, mailbox, queue, certificate and backup timer without a resident process.

Create /usr/local/sbin/mail-health:

#!/bin/bash
set -u
FAILED=0

echo '========================================'
echo ' MAIL SERVER HEALTH CHECK'
echo " $(date)"
echo '========================================'
echo
echo '=== SERVICE STATUS ==='
for SERVICE in caddy postfix dovecot rspamd fail2ban php8.5-fpm
do
    if systemctl is-active --quiet "$SERVICE"; then
        echo "[OK] $SERVICE"
    else
        echo "[FAIL] $SERVICE"
        FAILED=1
    fi
done

echo
echo '=== MEMORY ==='
free -h
AVAILABLE=$(awk '/MemAvailable:/ {print int($2/1024)}' /proc/meminfo)
if [ "$AVAILABLE" -lt 150 ]; then
    echo '[WARNING] Available RAM below 150 MiB'
    FAILED=1
fi

echo
echo '=== DISK ==='
df -h /
DISK=$(df --output=pcent / | tail -1 | tr -dc '0-9')
if [ "$DISK" -ge 80 ]; then
    echo '[WARNING] Disk usage above 80%'
    FAILED=1
fi

echo
echo '=== MAILBOX STORAGE ==='
du -sh /var/vmail

echo
echo '=== MAIL QUEUE ==='
postqueue -p

echo
echo '=== TLS CERTIFICATE ==='
CERT='/etc/letsencrypt/live/mail.example.com/cert.pem'
openssl x509 -in "$CERT" -noout -enddate
if openssl x509 -in "$CERT" -checkend 1209600 -noout; then
    echo '[OK] Certificate valid for at least 14 days'
else
    echo '[WARNING] Certificate expires soon or cannot be read'
    FAILED=1
fi

echo
echo '=== BACKUP TIMER ==='
if systemctl is-active --quiet mail-backup.timer; then
    echo '[OK] Backup timer active'
else
    echo '[FAIL] Backup timer inactive'
    FAILED=1
fi

echo
echo '=== FAILED SYSTEM SERVICES ==='
systemctl --failed --no-pager
echo '========================================'
exit "$FAILED"
sudo chmod 700 /usr/local/sbin/mail-health
sudo bash -n /usr/local/sbin/mail-health
sudo mail-health

The original script checks a 150 MiB available-memory warning level, 80% root filesystem usage, and a 14-day certificate validity window (1,209,600 seconds). It outputs queue contents and failed system services, but a nonempty queue does not automatically set its failure status, and it does not validate every protocol or remote backup timestamp. The monitoring output goes to the journal, not an external alerting service. These are intentional limitations of the current lightweight implementation; inspect the log periodically. If improving it later, add failure handling for each diagnostic, count or age queued messages, verify the latest backup age and implement an independent alerting channel. An email alert sent by the broken server itself is insufficient for detecting all mail outages.

19.5 Schedule health checks

/etc/systemd/system/mail-health.service:

[Unit]
Description=Mail Server Health Check

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/mail-health

/etc/systemd/system/mail-health.timer:

[Unit]
Description=Daily Mail Server Health Check

[Timer]
OnCalendar=*-*-* 07:00:00 UTC
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now mail-health.timer
sudo systemctl start mail-health.service
sudo journalctl -u mail-health.service -n 80 --no-pager
sudo systemctl list-timers --all | grep -E 'mail-health|mail-backup|certbot|logrotate'

The health timer is scheduled after the overnight backup to make manual inspection convenient. The original backup timer, Certbot timer and logrotate timer were directly observed active; the maintenance health timer was configured in subsequent instructions and the owner reported everything working. Verify its actual next/last execution locally.

19.6 Mailbox quotas and attachment limits

We intentionally did not impose a hard mailbox quota during the core build because the mailbox was very small and storage was plentiful. A quota can prevent delivery of legitimate mail when full. With three personal accounts, monitor aggregate disk growth and set limits only after choosing a realistic budget and handling full mailboxes safely. A future 10 GiB allowance was discussed, not applied. Three independent 10 GiB allowances would nearly consume the available disk, so do not blindly multiply that suggestion.

Dovecot has a quota plugin suitable for later configuration; use version-matched documentation and LMTP/IMAP tests. Reserve space for OS updates, application files, indexes, logs, queue and temporary data. Also watch Google Drive quota. The selected PHP upload limits do not guarantee a particular attachment size through Postfix or DNSExit.

19.7 Final maintenance schedule

Routine Example schedule (UTC) Mechanism
Encrypted mailbox backup Daily at 02:00 mail-backup.timer
Daily OS log rotation Varies with system timer logrotate.timer
Health check Daily at 07:00 mail-health.timer
Certbot renewal checks Automatic schedule certbot.timer and deployment hook
HTTPS certificate renewal Automatic as needed Caddy
Review failed authentication / spam Regular manual review Fail2ban and Rspamd logs
Backup integrity and restore drills Periodic manual review Restic check and test restore
Backup retention/pruning Manual initially Restic forget/prune
DNSExit renewal and quota review Before plan expiration and as needed DNSExit dashboard
OS / Roundcube security updates Regularly and promptly for critical fixes apt and upstream release checks

After maintenance changes, add their paths to the backup script (already represented in Section 15), validate it with bash -n, and create a fresh backup. This captures LMTP/Sieve and monitoring settings that the earlier observed snapshots did not yet contain.

20. Add independent mailboxes

20.1 Desired extension and what changes

The owner requested these two accounts:

[email protected] -> [email protected]
[email protected] -> [email protected]

They should be independent mailboxes, not merely aliases into reader's Inbox. An alias is an alternative delivery address that can point into an existing mailbox. A virtual account adds its own authentication record, physical mailbox, preferences, and sender permission. In this case each account needs its own Gmail copy as well. We use the same servers, certificates, filtering, DNS, relay account and backup repository. No new Linux account, VM, domain, or public port is required.

This extension was designed and documented in the final assistant instructions, but no output from account creation or per-account tests was supplied before this document. Execute or verify the following before claiming the two accounts are live. The existing reader account must continue working throughout.

20.2 Four mappings for every account

File Entry needed Purpose
/etc/dovecot/virtual-users Public address plus password hash, UID/GID, home Authentication for IMAP and SMTP submission
/etc/dovecot/mailbox-users Public and internal address entries pointing to same home Userdb for login and LMTP
/etc/postfix/vmailbox Internal delivery address SMTP recipient validation
/etc/postfix/sender_login_maps Public envelope sender -> public SASL username Outgoing authorization

Additionally create the Maildir, verify the two Cloudflare destinations per account, add the Worker's recipient mapping and create the public Cloudflare routing rule. No per-user Sieve script is necessary because the spam filter is server-wide. SQLite automatically associates webmail preferences and contacts with the respective Roundcube user.

20.3 Back up and check prerequisites

sudo install -d -m 700 /root/before-new-mailboxes
sudo cp -a /etc/postfix /root/before-new-mailboxes/
sudo cp -a /etc/dovecot /root/before-new-mailboxes/
sudo postconf virtual_transport virtual_mailbox_maps
sudo postconf -P submission/inet/smtpd_sender_login_maps
sudo doveconf -n | grep -E 'passwd_file_path|mail_path|mail_driver'
id vmail

The transport should be lmtp:unix:private/dovecot-lmtp, the mailbox map hash:/etc/postfix/vmailbox, and the submission sender map hash:/etc/postfix/sender_login_maps. Dovecot must use the two separate database files. If the live system differs, adapt the script instead of writing records into files that the services no longer use.

20.4 Reusable account provisioning script

The final setup provided a command called mail-add-user, accepting a simple lowercase local part. The script is reproduced below as the proposed provisioning utility. It reads the actual UID/GID, prompts for a private password, hashes it, saves a local configuration backup, creates the Maildir, appends the mappings, rebuilds Postfix maps and reloads services. It is not a transactional provisioning system: a failure after some writes can leave a partial account. Stop and inspect the backup and current mappings before retrying. Do not run it concurrently with manual edits or delete an account's existing mail to work around a duplicate-entry error.

Create /usr/local/sbin/mail-add-user:

#!/bin/bash
set -euo pipefail
umask 077

if [[ $EUID -ne 0 ]]; then
    echo 'Run this command using sudo.'
    exit 1
fi
if [[ $# -ne 1 ]]; then
    echo 'Usage: sudo mail-add-user username'
    exit 1
fi
USERNAME="$1"
if [[ ! "$USERNAME" =~ ^[a-z0-9][a-z0-9_-]{0,31}$ ]]; then
    echo 'Invalid username.'
    exit 1
fi

DOMAIN='example.com'
INTERNAL_DOMAIN='inbox.example.com'
EMAIL="$USERNAME@$DOMAIN"
INTERNAL_EMAIL="$USERNAME@$INTERNAL_DOMAIN"
MAIL_HOME="/var/vmail/$USERNAME"
VMAIL_UID=$(id -u vmail)
VMAIL_GID=$(id -g vmail)
PASSDB='/etc/dovecot/virtual-users'
USERDB='/etc/dovecot/mailbox-users'
VMAILBOX='/etc/postfix/vmailbox'
SENDER_MAP='/etc/postfix/sender_login_maps'

exec 9>/run/lock/mail-add-user.lock
flock -n 9 || exit 1

for FILE in "$PASSDB" "$USERDB" "$VMAILBOX" "$SENDER_MAP"
do
    if [[ ! -f "$FILE" ]]; then
        echo "Missing configuration file: $FILE"
        exit 1
    fi
    if awk -F '[:[:space:]]+' -v a="$EMAIL" -v b="$INTERNAL_EMAIL" \
        '$1 == a || $1 == b {found=1} END {exit !found}' "$FILE"
    then
        echo "Account entry already exists in $FILE."
        exit 1
    fi
done
if [[ -e "$MAIL_HOME" ]]; then
    echo 'Mailbox directory already exists.'
    exit 1
fi

echo "Creating account: $EMAIL"
read -r -s -p 'Enter mailbox password: ' PASSWORD </dev/tty
echo
read -r -s -p 'Confirm mailbox password: ' CONFIRM </dev/tty
echo
if [[ "$PASSWORD" != "$CONFIRM" ]]; then
    echo 'Passwords do not match.'
    exit 1
fi
if [[ ${#PASSWORD} -lt 16 ]]; then
    echo 'Use a password of at least 16 characters.'
    exit 1
fi
HASH=$(printf '%s\n' "$PASSWORD" | openssl passwd -6 -stdin)
unset PASSWORD CONFIRM

BACKUP=$(mktemp -d /root/mail-user-backup.XXXXXXXX)
cp -a "$PASSDB" "$USERDB" "$VMAILBOX" "$SENDER_MAP" "$BACKUP/"
echo "Configuration backup: $BACKUP"

install -d -o vmail -g vmail -m 700 \
    "$MAIL_HOME" \
    "$MAIL_HOME/Maildir" \
    "$MAIL_HOME/Maildir/cur" \
    "$MAIL_HOME/Maildir/new" \
    "$MAIL_HOME/Maildir/tmp"

printf '\n%s:{SHA512-CRYPT}%s:%s:%s::%s::\n' \
    "$EMAIL" "$HASH" "$VMAIL_UID" "$VMAIL_GID" "$MAIL_HOME" >> "$PASSDB"
printf '\n%s::%s:%s::%s::\n' \
    "$EMAIL" "$VMAIL_UID" "$VMAIL_GID" "$MAIL_HOME" >> "$USERDB"
printf '%s::%s:%s::%s::\n' \
    "$INTERNAL_EMAIL" "$VMAIL_UID" "$VMAIL_GID" "$MAIL_HOME" >> "$USERDB"
printf '\n%s %s/Maildir/\n' "$INTERNAL_EMAIL" "$USERNAME" >> "$VMAILBOX"
printf '\n%s %s\n' "$EMAIL" "$EMAIL" >> "$SENDER_MAP"
unset HASH

chown root:dovecot "$PASSDB" "$USERDB"
chmod 640 "$PASSDB" "$USERDB"
postmap "hash:$VMAILBOX"
postmap "hash:$SENDER_MAP"
doveconf -n >/dev/null
postfix check
systemctl reload dovecot
systemctl reload postfix

echo
echo '========================================'
echo 'Account created successfully'
echo "Email: $EMAIL"
echo "Internal address: $INTERNAL_EMAIL"
echo "Mailbox: $MAIL_HOME"
echo 'Webmail: https://mail.example.com'
echo '========================================'
sudo chmod 700 /usr/local/sbin/mail-add-user
sudo bash -n /usr/local/sbin/mail-add-user && echo 'Syntax OK'
sudo mail-add-user research
sudo mail-add-user engineering

Use two different, randomly generated passwords of at least 16 characters. They are entered privately in the terminal, not posted in chat or embedded in the script. The username regex rejects path separators and unusual characters, which helps keep mailbox paths and mapping syntax predictable. flock prevents two instances of this helper from writing simultaneously. The script preserves the existing account records by appending; it does not overwrite the whole databases.

For a more robust future provisioning tool, stage and validate new map files, use atomic replacements where appropriate, add an explicit rollback path, and verify Dovecot and Postfix lookups after changes. This is not necessary for the two controlled personal accounts if the manual verification below is done carefully.

20.5 Verify the local databases and mailbox isolation

The following are the expected complete mailbox lookups after adding both accounts (substitute the real UID/GID if they changed):

# /etc/dovecot/mailbox-users
[email protected]::5000:5000::/var/vmail/reader::
[email protected]::5000:5000::/var/vmail/reader::
[email protected]::5000:5000::/var/vmail/research::
[email protected]::5000:5000::/var/vmail/research::
[email protected]::5000:5000::/var/vmail/engineering::
[email protected]::5000:5000::/var/vmail/engineering::
# /etc/postfix/vmailbox
[email protected] reader/Maildir/
[email protected] research/Maildir/
[email protected] engineering/Maildir/
# /etc/postfix/sender_login_maps
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected]

Do not print /etc/dovecot/virtual-users into a public terminal transcript; inspect only the account-name field if needed:

sudo cut -d: -f1 /etc/dovecot/virtual-users
sudo cat /etc/dovecot/mailbox-users
sudo cat /etc/postfix/vmailbox
sudo cat /etc/postfix/sender_login_maps
sudo doveadm auth login [email protected]
sudo doveadm auth login [email protected]
sudo doveadm user -x service=lmtp [email protected]
sudo doveadm user -x service=lmtp [email protected]
sudo postmap -q [email protected] hash:/etc/postfix/vmailbox
sudo postmap -q [email protected] hash:/etc/postfix/vmailbox
sudo postmap -q [email protected] hash:/etc/postfix/sender_login_maps
sudo postmap -q [email protected] hash:/etc/postfix/sender_login_maps

Each userdb result must point to its own home. The Dovecot auth command must succeed with the account's own password. The internal address should not authenticate as an independent public account. Log into Roundcube for both using separate browser profiles or sessions, and confirm neither sees reader's existing messages. A maildir-level inspection should show three distinct directories. All share vmail ownership but Dovecot selects the account-specific home.

The new accounts may initially have empty Inboxes; the standard special folders are created automatically by Dovecot/Roundcube. If one is missing, check the namespace and create it using the account's authenticated IMAP context rather than changing filesystem permissions broadly.

20.6 Verify new destinations in Cloudflare

In Email Routing -> Destination Addresses add and verify these four destinations:

Destination Verification message appears in
[email protected] Research Roundcube mailbox
[email protected] Academic Gmail account
[email protected] Engineering Roundcube mailbox
[email protected] Developer Gmail account

The internal recipients are now accepted by Postfix and mapped by Dovecot. They can receive verification messages before their public routing rules are created. If the link is missing, check the correct account's Junk folder and the Postfix queue. Do not remove reader's existing verified destinations. The DNS for inbox.example.com already routes every local part at that internal domain to the same Postfix server; recipient maps, not new MX records, distinguish the addresses.

20.7 Upgrade the existing Worker to recipient-based routing

Save a copy of the old Worker code first. In Cloudflare Workers & Pages, open example-mail-router, edit its email handler and deploy the following complete code:

const ROUTES = {
	'[email protected]': ['[email protected]', '[email protected]'],
	'[email protected]': ['[email protected]', '[email protected]'],
	'[email protected]': ['[email protected]', '[email protected]']
};

export default {
	async email(message, env, ctx) {
		const recipient = message.to.toLowerCase();
		const destinations = ROUTES[recipient];

		if (!destinations) {
			message.setReject('Unknown recipient');
			return;
		}

		const results = await Promise.allSettled(
			destinations.map((destination) => message.forward(destination))
		);

		results.forEach((result, index) => {
			if (result.status === 'fulfilled') {
				console.log(`Forwarded ${recipient} to ${destinations[index]}`);
			} else {
				console.error(
					`Forwarding failed: ${recipient} to ${destinations[index]}`,
					String(result.reason)
				);
			}
		});

		if (results.every((result) => result.status === 'rejected')) {
			throw new Error('All forwarding destinations failed');
		}
	}
};

The routing table is a map from the actual inbound envelope address to exactly two allowed destinations. The current recipient is normalized to lowercase, matching the provisioned lowercase usernames. An unknown recipient is rejected rather than silently being delivered to reader. This design prevents accidentally mixing Research and Engineering messages. If using plus-addressing or an alias later, define and test its exact routing policy; the current table does not implement those features.

The handler awaits all deliveries, logs each success/failure and throws if both fail. As before, one successful branch does not guarantee the other will be retried. The handler does not store the raw mail in a queue or maintain a separate delivery ledger. Preserve a local copy of this code and the routing table in private storage: the original Restic backup does not automatically export Cloudflare Workers.

20.8 Add public routing rules

Create these rules after local mailboxes and verified destinations are ready and the Worker is deployed:

Public custom address Action Destination
[email protected] Send to a Worker example-mail-router (existing rule)
[email protected] Send to a Worker example-mail-router
[email protected] Send to a Worker example-mail-router

Disable the temporary [email protected] route if it is no longer required, because it is not in the new Worker map. Avoid enabling a catch-all unintentionally. A catch-all will not create Dovecot users, and unknown recipients should not silently fall into the wrong mailbox. Cloudflare has account/routing limits and verified-destination limits; check the current provider limits when scaling beyond a few accounts.

20.9 Configure identities and test every path

In each Roundcube account, Settings -> Identities should show its own exact public address. Set a display name appropriate to the owner; for example, the academic mailbox may use an academic signature and the developer mailbox a professional engineering signature. Leave Bcc and Reply-To empty unless there is an explicit reason to set them. Never change the sender identity to another account just because the domain is the same.

Use an independent sender account, preferably not the target account's Gmail forwarding destination, and a unique subject for each test. Verify:

  • Send to Research: the message appears in Research Roundcube and academic Gmail, not reader or Engineering.
  • Send to Engineering: the message appears in Engineering Roundcube and developer Gmail, not reader or Research.
  • Send to reader: the original account still receives both local and Gmail copies.
  • Send from Research and Engineering through Roundcube to an independent recipient; check the actual Gmail Show original header for SPF/DKIM/DMARC alignment and the correct public From address.
  • Verify both accounts' Sent folders, separate mailbox contents, and standard Junk folders.
  • Attempt an authenticated submission with one account's credentials and the other account's envelope sender in a controlled RCPT-only test; the sender-login map should reject it. This is separate from From-header authorization and should not deliver a message to any real third party.
  • Confirm a nonexistent internal address is rejected at RCPT.
sudo journalctl --since '10 minutes ago' \
  | grep -E 'postfix/lmtp|dovecot.*lmtp|status=sent'
sudo postqueue -p
sudo doveadm mailbox status -u [email protected] 'messages unseen' INBOX Junk
sudo doveadm mailbox status -u [email protected] 'messages unseen' INBOX Junk

Because the domain is already authorized by DNSExit, new local parts should not require a second DKIM selector or relay account. That is an assumption about the provider's sender policy; verify both outbound tests. The daily recipient quota remains shared across all three accounts. A compromised mailbox credential could exhaust the quota for everyone, so unique passwords and abuse monitoring matter.

20.10 Back up the expansion and manage future accounts

The existing backup already contains /var/vmail, Postfix and Dovecot databases and the shared Roundcube database. Include /usr/local/sbin/mail-add-user as a path (Section 15 includes it in the optional list). Back up the Worker code and Cloudflare route/destination inventory separately, or put a private copy in a deliberate backed-up directory. Do not add a sensitive configuration file to a public website repository.

sudo bash -n /usr/local/sbin/mail-backup && sudo mail-backup
sudo mail-restic snapshots --latest 1

For future creation of a fourth account, the conceptual procedure is the same:

sudo mail-add-user business

Then verify the local user, add its two verified Cloudflare destinations, update the Worker map, add the public route, test and back up. The helper automates server files, not the Cloudflare dashboard or provider policies.

For a password change, securely generate a new hash on the server, replace only the intended account's hash in virtual-users while preserving all other fields/records, keep root:dovecot mode 640, and reload Dovecot. A password-change self-service plugin was not installed. A changed mailbox password affects both IMAP and authenticated submission, but it does not change the account's Gmail forwarding destination or DNSExit password. Do not use an editor operation that exposes a secret to other users or logs. Revoke active sessions if the change is due to suspected compromise.

For a mailbox retirement, first disable its public route and remove its Worker mapping, decide how to archive its messages, then disable its authentication and incoming recipient mapping. Rebuild maps and verify other accounts. Do not immediately delete its Maildir: retained backups and a deliberate archival plan are safer. No destructive removal utility was installed during this build.

21. Client configuration and everyday use

21.1 Connection settings

Setting Value
Webmail https://mail.example.com
Incoming protocol IMAP
Incoming hostname mail.example.com
Incoming port 993
Incoming encryption SSL/TLS from start
Outgoing hostname mail.example.com
Outgoing port 587
Outgoing encryption STARTTLS, required
Authentication Normal password over TLS
Username (both directions) Full public email address
Password The matching Dovecot mailbox password

The account password is not the Gmail password and not the DNSExit relay credential. The user authenticates to Postfix/Dovecot; Postfix separately authenticates to DNSExit. The internal @inbox.example.com address is for forwarding, not user login. Clients should use the mail hostname rather than a raw IP to preserve TLS hostname verification.

21.2 Apple Mail, Thunderbird and other clients

On macOS, open System Settings -> Internet Accounts -> Add Account -> Add Other Account -> Mail Account (the exact wording can change by OS version). Enter the public email address and its password. If automatic discovery fails, choose IMAP and enter the hostnames/ports above manually. In Mail account settings, disable automatic connection-setting management only if it prevents selecting the correct ports and TLS modes. For Thunderbird, select Manual Configuration if necessary. No autodiscovery DNS records or profiles were configured in the original build.

Use IMAP rather than POP3 to synchronize folders across clients. Verify the client's special folders correspond to Drafts, Sent, Junk and Trash rather than storing duplicates under separate client-specific folders. Do not accept a certificate mismatch. If the external ports do not connect, test the network and OCI/Linux firewall; Roundcube working locally does not prove that external IMAP is reachable.

21.3 Gmail forwarding is receive-only duplication

The destination Gmail account receives a copy of new inbound messages. It does not automatically become a sending identity for the custom domain. Replying directly from that Gmail account ordinarily sends from the Gmail address. For the custom From address use Roundcube or a configured mail client. Gmail's separate Send mail as feature, where supported for the user's account, would require a new deliberate SMTP setup and verification; it was not configured in this build.

Deleting a message in Gmail does not delete the local Maildir copy. Moving a message into Roundcube's Junk does not update Gmail. A forwarded copy may land in Gmail's spam folder even when the local copy is in INBOX, because the two classifiers operate independently. Check the local mailbox regularly for authoritative storage, and use independent encrypted backups to recover lost mail.

22. Troubleshooting and incident playbook

22.1 Diagnose the correct layer first

A mail system has multiple independent boundaries. Do not make random changes to DNS, TLS, passwords and firewall rules simultaneously. Reproduce the issue, note exact timestamps/recipient/direction and locate the first boundary where the expected event is missing.

DNS -> cloud ingress -> host firewall -> listener -> TLS -> SMTP policy
    -> recipient map -> spam filter -> queue -> LMTP -> userdb -> Sieve/Maildir
    -> IMAP authentication -> webmail

For outgoing mail, substitute client authentication -> submission sender policy -> queue -> relay authentication and TLS -> DNSExit -> recipient. For duplicate Gmail delivery, inspect the Worker branch separately; the Oracle mail logs do not show the Gmail branch.

22.2 Common problems actually encountered

Symptom What it meant in this build Resolution
Port 25 test failed from one network Network-specific path could be restricted, while other nodes could reach the listener Test from multiple locations, verify OCI and iptables; retain TCP 25 for inbound MX delivery
sudo cat .../new/* did not work Shell glob expansion happened before root privileges in a protected directory Use a root shell for the glob; keep restrictive permissions
Dovecot login rejected a password Actual stored hash did not match the entered password Regenerate hash securely, check logs and doveadm auth login
TLS validation failed connecting to 127.0.0.1 Certificate is issued to DNS hostname, not the loopback IP Validate hostname explicitly, keep trust verification on
DNSExit 454 after successful AUTH Relay accepted credentials but temporarily rejected message DATA Inspect provider status/quota, queue retry; subsequent delivery succeeded
Gmail duplicate landed in spam Authentication passed but recipient spam classification differed Mark legitimate mail not spam; investigate headers and reputation, do not disable security
550 5.1.1 Address does not exist Public Cloudflare routing rule was missing Add/activate route for real public address and resend
Caddy warning about unformatted file Syntax was valid; formatting warning only caddy fmt --overwrite, validate and reload
Roundcube errors.log absent Login failure existed in userlogins.log instead Monitor the actual login file
Built-in Roundcube Fail2ban filter matched zero lines Log format had extra session/forwarding fields Custom anchored regex, test exactly one failure match
Google OAuth Publish disabled External app branding not complete Use supported personal OAuth configuration for the owner or complete legitimate consent setup
Headless OAuth prompt config_token> VM waiting for browser-based authorization token Authorize using Rclone on Mac, securely paste token into VM
Synthetic Rspamd email flagged as spam Artificial message lacked Date, Message-ID and real authentication Expected test result; use real mail for tuning
LMTP direct tests needed different recipient Public login and internal forwarding address differ Separate userdb contains both mapped to same home
Bash syntax error near /etc/systemd/journald.conf.d Missing continuation after mail-backup.timer Correct continuation list, validate with bash -n, rerun backup

22.3 Quick diagnosis by symptom

No incoming message anywhere:

dig MX example.com +short
dig MX inbox.example.com +short
sudo postqueue -p
sudo journalctl --since '15 minutes ago' | grep postfix

Check the Cloudflare Email Routing activity log, routing rule and Worker logs. If no SMTP attempt reaches Oracle, inspect the internal forwarding destination verification, subdomain MX, port 25 path and Worker outcome. If both forwarding branches fail, do not assume a successful SMTP status just because a Worker event exists.

Gmail receives the copy but Oracle does not: check the local branch of the Worker, internal destination, OCI ingress, Postfix recipient map, queue, LMTP socket and userdb. A successful Gmail copy proves the external inbound route worked, not the local branch.

sudo postmap -q [email protected] hash:/etc/postfix/vmailbox
sudo doveadm user -x service=lmtp [email protected]
sudo ls -l /var/spool/postfix/private/dovecot-lmtp
sudo journalctl --since '15 minutes ago' | grep -E 'postfix/lmtp|dovecot.*lmtp|sieve'
sudo doveadm mailbox status -u [email protected] 'messages unseen' INBOX Junk

Oracle receives the message but Gmail does not: check the Gmail branch log, verified destination, Gmail Spam/All Mail and storage availability. Avoid repeatedly forwarding the same message until you know which branch succeeded; partial success can cause duplicates.

Roundcube cannot load (502/500):

sudo systemctl is-active caddy php8.5-fpm
sudo ls -l /run/php/roundcube.sock
sudo php-fpm8.5 -t
sudo php -l /var/www/roundcube/config/config.inc.php
sudo journalctl -u caddy -n 50 --no-pager
sudo journalctl -u php8.5-fpm -n 50 --no-pager
sudo ls -lah /var/log/roundcube/

A PHP error is different from a socket permission error. Check the socket owner/group and Caddy service identity. Do not set it to mode 777 or make the Roundcube application directory world-writable as a shortcut.

Roundcube loads but login fails:

sudo doveadm auth login [email protected]
sudo doveadm user [email protected]
sudo journalctl -u dovecot -n 50 --no-pager
sudo fail2ban-client status roundcube-auth
sudo fail2ban-client status dovecot

Inspect whether the browser connection is blocked or whether backend authentication failed. Check the Dovecot password, UID/GID and TLS verification. The original failure was a password mismatch, not a need to expose insecure IMAP.

Outgoing email is not delivered:

sudo postqueue -p
sudo postconf relayhost smtp_sasl_auth_enable smtp_tls_security_level
sudo journalctl --since '15 minutes ago' | grep postfix

Locate the relevant queue ID. status=deferred plus a 4xx indicates a transient issue; inspect the relay's response and retry schedule. status=bounced indicates a permanent failure. status=sent to DNSExit means the relay accepted the message, not necessarily that the final recipient placed it in Inbox. Review DNSExit's tracking dashboard and Gmail headers. Check quota and expiration. sudo postqueue -f requests a queue flush; use it after fixing the cause, not repeatedly during a provider outage. Never delete all queued messages to hide a problem.

Mail lands in Junk: inspect X-Spamd-Result, X-Rspamd-Action and the actual authentication results. Recover the message by moving it out of Junk. A zero-point symbol is not an automatic spam indicator. Do not globally whitelist every Cloudflare forwarded message: spammers can send through a public mail route too.

Wrong account receives mail: disable the affected new public rule if leakage is occurring. Check the Worker's message.to mapping and destination verification, then Dovecot userdb and mailbox ownership. Do not manually copy messages between homes until the routing problem is fixed and the privacy impact understood.

Backup failure:

sudo bash -n /usr/local/sbin/mail-backup
sudo systemctl status mail-backup.service --no-pager
sudo journalctl -u mail-backup.service -n 100 --no-pager
sudo rclone --config /etc/mail-backup/rclone.conf about gdrive:
sudo mail-restic snapshots

Check OAuth expiry/revocation, available Drive storage, network errors, wrong repository password, missing source paths, SQLite errors and repository locks. Do not reinitialize a repository or delete a lock merely because a command timed out. Confirm no other Restic process is using it before following the installed version's documented unlock procedure. Keep the old encrypted snapshots intact while investigating.

Certificate renewal failure: inspect Certbot timer history and renewal configuration, token permissions, DNS challenge propagation and CA error. Run a controlled --dry-run after correcting the cause. Verify service reload and served certificate validity. Do not request production certificates repeatedly or turn TLS verification off. Caddy's certificate and the mail certificate are separate systems.

22.4 Useful safe logging commands

sudo journalctl -u caddy -n 50 --no-pager
sudo journalctl -u dovecot -n 50 --no-pager
sudo journalctl --since '10 minutes ago' | grep postfix
sudo journalctl -u fail2ban -n 50 --no-pager
sudo tail -n 50 /var/log/rspamd/rspamd.log
sudo tail -n 20 /var/log/roundcube/userlogins.log
sudo journalctl -u mail-backup.service -n 50 --no-pager
sudo journalctl -u mail-health.service -n 80 --no-pager
sudo systemctl --failed --no-pager

Redact message bodies, personal email addresses where unnecessary, client IPs, authentication tokens, passwords, hashes, cookies and session identifiers before sharing diagnostics outside trusted support channels. Never expose postcat/raw queue contents or private key files publicly; queue and log data may include private correspondence.

23. Disaster recovery and rebuilding the platform

23.1 Decide what the backup actually contains

The encrypted backup is file-level and mail-focused. It includes Maildir, selected configs, virtual user maps, relay credentials, Certbot files, Roundcube config/plugins, consistent SQLite backup, Rspamd data, Fail2ban and maintenance scripts. It records the installed package list and original virtual UID/GID. It does not automatically include a full OCI image, all installed package binaries, full Roundcube application release, Caddy's certificate cache, full website code, pending Postfix queue, external Cloudflare Worker definitions, DNS zone/rules, OCI firewall/instance metadata, DNSExit account or Google OAuth recovery credentials.

An empty queue at the time of the reported diagnostics is good, but messages accepted after the last backup or held in a queue can still be lost in a disaster. A daily schedule implies a potential local-mail recovery point of roughly the last successful daily backup, not guaranteed zero loss. Gmail copies may help recover some newer incoming mail, but will not necessarily cover every branch or outgoing message. Restore duration depends on bandwidth, repository size and available infrastructure; it was not measured in this build.

23.2 Maintain an external recovery kit

Store securely outside the VM:

  • Restic repository password and repository location (rclone:gdrive:example-mail-backup).
  • Google account recovery access and the original OAuth project/client credentials or securely stored authorization configuration. With drive.file, a different app may not see existing backup files.
  • SSH private key and information needed to access the OCI account/console, or a safe recovery procedure.
  • Cloudflare account recovery, domain registrar access, DNS zone record inventory, destination-address list and current Worker source.
  • DNSExit account recovery and current plan/relay settings.
  • The actual installed software versions, upstream release URL/checksum and any customized application code or plugins.
  • This private runbook and notes on any configuration changes after its date.

Do not put plaintext secrets in a normal Google Drive folder or this Markdown file. Use a trusted password manager or other encrypted independent storage. Test that the kit can be retrieved without the Oracle VM. If root on the server is compromised, rotate affected secrets rather than blindly trusting a backup of credentials that may already have been stolen.

23.3 Restore to a staging directory first

On a replacement Ubuntu VM with appropriate access, install Restic and Rclone, recreate /etc/mail-backup with mode 700, recover the same repository password privately, and reconnect using the original Google OAuth app where possible. Restore the mail-restic wrapper from this document or a trusted copy. Do not call restic init for an existing repository.

sudo mail-restic snapshots
sudo mail-restic check
sudo install -d -m 700 /root/mail-recovery
sudo mail-restic restore latest --tag mail-server --target /root/mail-recovery
sudo du -sh /root/mail-recovery/var/vmail
sudo sqlite3 /root/mail-recovery/var/backups/mail-server/roundcube.sqlite \
  'PRAGMA integrity_check;'
sudo cat /root/mail-recovery/var/backups/mail-server/vmail-user.txt
sudo cat /root/mail-recovery/var/backups/mail-server/vmail-group.txt

A real recovery should deliberately choose the most suitable verified snapshot ID, not necessarily the newest if a corruption or compromise occurred. Keep the old repository and original machine (if available) intact while validating the replacement. For a staged recovery do not route production SMTP traffic into the new host before it is ready.

23.4 Restore services in a safe order

  1. Infrastructure: create replacement VM, configure SSH and OCI network policies, install OS updates and required packages, preserve or recreate the website deployment separately. Check the new public IP. Do not expose the new SMTP listeners until configuration and relay restrictions are validated.
  2. Service identities: recreate vmail with the original UID/GID if available without conflict, or deliberately remap Maildir ownership, Dovecot user records and Postfix virtual UID/GID settings to the new IDs. Do not overwrite /etc/passwd or /etc/group wholesale. Package-created users (postfix, dovecot, www-data, caddy) should be created by the package/service installation and checked.
  3. Packages and versions: reinstall compatible Postfix, Dovecot with LMTP/Sieve, PHP-FPM, Caddy, Fail2ban, Certbot DNS plugin and Rspamd. Use the stored package list for reference rather than blindly installing every historical version. Reinstall the supported compatible Roundcube complete release using a trusted archive and consult migration instructions if its schema changes.
  4. Configuration and secrets: review restored /etc/postfix, /etc/dovecot, /etc/rspamd, /etc/caddy, /etc/fail2ban, PHP-FPM and relevant systemd files, then selectively install them with original or correctly mapped ownership/modes. Restore password hash files and relay credential map source without displaying secrets. Rebuild all Postfix hash maps with postmap and recompile the Sieve script using sievec.
  5. Mailbox and database: stop or isolate the destination services before copying production data. Restore /var/vmail preserving metadata and ensure all homes map to the correct service IDs. Restore the consistent SQLite copy from var/backups/mail-server/roundcube.sqlite into /var/lib/roundcube/roundcube.sqlite with www-data:www-data, mode 600. Ensure the directory and temp/log paths exist and are correctly owned. On a fresh host there should not be stale database WAL/journal files; on a replacement of an existing database, stop the application and preserve the old database and journal files safely before installing the recovered copy. Do not merge SQLite databases by copying files over a running PHP process.
  6. TLS: restore /etc/letsencrypt including archive and renewal files or issue a new certificate using a valid scoped DNS token. Preserve symlinks and private key permissions; inspect expiry and hostname. Caddy can reissue its own HTTPS certificates once DNS points to the new origin. Avoid repeated CA issuance attempts. Test certificate reload hooks.
  7. Network and validation: reconstruct the required OCI ingress and Linux firewall rules for the new machine instead of blindly copying the old firewall dump. Confirm Rspamd and PHP-FPM/Bun remain local. Test doveconf -n, postfix check, rspamadm configtest, php-fpm8.5 -t, caddy validate, fail2ban-client -t, and Bash scripts. Confirm map lookups, secure logins, rejection of unauthenticated relay, and local LMTP delivery to both INBOX and Junk. Start services and inspect logs.
  8. Cutover: update the mail A record to the replacement IP (DNS only); update the website's A record if it also moved. Keep the public Cloudflare MX records and the internal subdomain MX unchanged unless the mail hostname itself changes. Verify propagation and external TLS/SMTP. Restore or verify the Worker and routing rules. Avoid having two servers both acting as the authoritative mailbox store after cutover.
  9. Acceptance and backups: test incoming delivery, Gmail copies, Roundcube outgoing delivery, per-account isolation, authentication, spam sorting, firewall bans, and queue health. Restore timers, create a new verified encrypted snapshot, perform another staging restore drill, and update the recovery kit with the new environment details.

Example of selectively rebuilding maps and compiling Sieve after verified files are restored:

sudo postmap hash:/etc/postfix/vmailbox
sudo postmap hash:/etc/postfix/sender_login_maps
sudo postmap hash:/etc/postfix/relay_passwd
sudo chmod 600 /etc/postfix/relay_passwd /etc/postfix/relay_passwd.db
sudo sievec /etc/dovecot/sieve/spam-filter.sieve
sudo doveconf -n >/dev/null
sudo postfix check
sudo rspamadm configtest
sudo php-fpm8.5 -t
sudo caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
sudo fail2ban-client -t

The precise copying commands intentionally depend on the replacement system's paths, version compatibility and service ownership. A blind restic restore --target / could overwrite live configurations, credentials and files irreversibly. Use staging, compare, then restore selectively. The procedure is a recovery plan, not an observed full-server restore from the build.

23.5 Rollback and incident priorities

Keep a working administrative SSH session or OCI console. During an incident, preserving existing data and preventing unauthorized use are more important than immediately restoring every optional feature. If spam filtering fails, the fail-open Milter policy can preserve delivery. If LMTP fails, revert the specific transport after verifying the old virtual map is valid. If Roundcube is compromised, disable or restrict webmail while retaining SMTP/IMAP where safe, investigate, patch and rotate secrets. If SMTP relay credentials leak, revoke/rotate them and monitor queued and sent messages. If the VM is compromised at root level, rebuild from a trusted image and rotate all affected credentials, including certificates if private keys were exposed.

Never recover by enabling an open relay, allowing plaintext Internet logins, disabling all security controls, changing permissions to 777, deleting the whole queue or replacing working databases without a backup. Such shortcuts can create a much worse outage.

24. Security review, limitations, and operating costs

24.1 Security layers and their actual scope

Layer Implemented or configured behavior Remaining caveat
OCI and Linux firewall Expose only intended public TCP ports; private worker/app sockets Verify effective firewall and IPv6 rules, SSH source restriction, ban chain ordering
TLS Certbot mail certificate, Caddy HTTPS, mandatory submission/IMAP TLS Periodic renewal and actual served-certificate checks required
Virtual user authentication Separate per-account password hashes and homes Shared vmail service UID is not strict OS multi-tenancy
SMTP relay policy Port 25 restricted; authenticated 587; envelope sender maps Verify external relay rejection and cross-account sender tests; visible From not independently enforced
Rspamd Incoming scoring, authentication/reputation/content checks Not antivirus; forced actions can still override threshold; fail-open accepts unscanned mail
Sieve Junk sorting for add header Verify forged-header handling through real SMTP; no automatic deletion
Fail2ban IMAP, SMTP and Roundcube jails Verify actual bad login detection and bans after upgrades/log rotation; IP rate limits are imperfect
Application hardening Roundcube public_html, protected config, TLS validation, installer disabled Prompt upstream security updates; verify no private files served
Domain authentication Incoming and outgoing SPF/DKIM/DMARC validated DMARC enforcement deferred; authentication not a spam or privacy guarantee
Encrypted backups Restic remote snapshots, root-only credentials Not immutable; restore drill and off-server secret recovery necessary
Monitoring Daily shell health check, journal retention No independent notification or full protocol probe; remote backup freshness not checked automatically

The internal inbox.example.com domain is public DNS with an MX, even though we call it internal. Any Internet sender able to reach TCP 25 can try delivering directly to a known internal address, bypassing Cloudflare's public route and Gmail duplication. The recipient restrictions protect against relay and unknown users, not against direct delivery to a valid recipient. If a strict Cloudflare-only ingress boundary is desired later, design a supported, maintained allowlist or authenticated transport using official current forwarding information, and test recovery/verification flows carefully. Do not copy a single observed Cloudflare IP into a permanent firewall allowlist; provider IPs can change.

24.2 Credentials inventory (names only)

Credential Purpose Where to keep it
Oracle SSH private key Admin access to the VM Trusted Mac / protected key store, independent backup
Mailbox password per account IMAP + SMTP submission Password manager; only hash in Dovecot file
DNSExit relay credential Outgoing relay authentication Root-only Postfix map; secure recovery storage
Cloudflare scoped DNS token DNS-01 certificate renewal Root-only /root/.secrets/cloudflare.ini
Certbot private key TLS server identity Protected /etc/letsencrypt lineage; encrypted backup
Roundcube application key Protect application session data Protected Roundcube config; encrypted backup
Google OAuth client/token Rclone access to Drive Root-only /etc/mail-backup/rclone.conf, secure independent recovery
Restic repository password Decrypt backups Root-only password file plus independent protected copy
Cloudflare/Google/DNSExit/OCI login and MFA External service administration Password manager and recoverable MFA/recovery codes

Rotate secrets if exposed. The fact that an encrypted Restic repository includes TLS keys and API/relay credentials makes its password particularly valuable. Do not share a raw repository unlock password just to ask someone to inspect a backup. Restrict administrative access and enable multi-factor authentication on external provider accounts where supported.

24.3 Operational limitations of the free design

This is a well-tested small personal mail system, not a highly available enterprise mail service. A single VM is a single point of failure. External providers control parts of delivery; there is no full control over their outages, quotas, policies or free-plan changes. Oracle Always Free resource availability and usage rules may change, and VM or account loss is possible. Incoming duplication is useful but not guaranteed atomic. A shared relay's reputation affects delivery. Disk and RAM are finite, and increasing the number of accounts does not increase relay quota.

No ClamAV, Redis-backed Bayesian classifier, ManageSieve, commercial monitoring suite, mailbox self-service password-change plugin, public Rspamd dashboard, or strict DMARC reject policy was installed during the core build. Those were consciously deferred. Do not expand the infrastructure merely for completeness; address observed needs, keep the system maintainable and prioritize recovery, security patches, provider renewals and deliverability.

24.4 Cost model at build time

Service Recorded cost / constraint
Oracle Cloud VM $0 within eligible Always Free resource limits
Cloudflare DNS and Email Routing $0 within free usage limits
Cloudflare Worker $0 within free limits; routing and forwarding limits apply
DNSExit relay $0 on selected free plan; 25 recipients/day shared; renewal every 180 days in recorded plan
Postfix, Dovecot, Rspamd, Fail2ban Open-source software, no license subscription
Caddy, PHP, SQLite, Roundcube Open-source software, no license subscription
Let's Encrypt certificates $0
Restic and Rclone Open-source tools
Google Drive backup $0 within available account storage quota
Domain registration Separate recurring expense, not part of the free VM/service calculation
Administrator time, Internet, device storage Not quantified

The recurring infrastructure subscription cost was effectively $0 within the selected provider limits, excluding domain renewal and any future paid upgrades. This is a historical cost structure, not a guarantee of future pricing. A paid relay or increased storage may become necessary if usage grows.

25. Command reference and maintenance

25.1 Everyday operations

Purpose Command
Overall health sudo mail-health
Available memory / swap free -h and swapon --show
Active memory pressure vmstat 1 5
Disk usage df -h /
Mailbox storage sudo du -sh /var/vmail
Mail queue sudo postqueue -p
Postfix settings sudo postconf -n
Per-service SMTP overrides sudo postconf -P
Dovecot effective configuration sudo doveconf -n
Test public mailbox credentials sudo doveadm auth login [email protected]
Test LMTP user lookup sudo doveadm user -x service=lmtp [email protected]
List IMAP folders sudo doveadm mailbox list -u [email protected]
Spam statistics sudo rspamc -h 127.0.0.1:11334 stat
Fail2ban jails sudo fail2ban-client status
Roundcube ban status sudo fail2ban-client status roundcube-auth
Firewall rules sudo iptables -L INPUT -n -v --line-numbers
Listening sockets sudo ss -lntp
Certificate expiry sudo certbot certificates
Certificate renewal test sudo certbot renew --cert-name mail.example.com --dry-run --run-deploy-hooks
Create new encrypted snapshot sudo mail-backup
List snapshots sudo mail-restic snapshots
Verify repository sudo mail-restic check
Automatic tasks systemctl list-timers --all
Backup service history sudo journalctl -u mail-backup.service
Health history sudo journalctl -u mail-health.service
Available package updates apt list --upgradable
Provision a new mailbox (after installing helper) sudo mail-add-user username

Commands that display configuration and logs can expose internal identifiers or sensitive information. Keep output private and redact credentials. Commands are intended for the owner/administrator on this VM.

25.2 Ongoing maintenance

Use the platform normally rather than continually installing more components. Keep the domain, relay account, cloud account and OAuth access valid. Check security releases and certificate expiration, watch the queue and disk, review backup success, and occasionally restore a sample. Do not treat the initial successful authentication test as a perpetual deliverability guarantee. If a specific new need appears (e.g. user-editable filters, higher sending volume, more users, immutable backups or multi-factor webmail), design that change independently and test it before expanding production.

26. Technical references

26.1 How to use these references

The examples reflect the architecture of a working personal mail system. Match the upstream documentation to your installed versions and check the effective configuration on your own machine before applying changes.

26.2 Official documentation for continued learning and maintenance

The following references support the technical design and provide the version-specific details needed when rebuilding or upgrading. Some are live project documentation and may change; the recorded configuration in this document remains tied to the original environment. External documentation is referenced rather than reproduced wholesale.

Topic Official reference
OCI network security and platform administration Oracle Cloud Infrastructure documentation
Cloudflare email routing rules and verified destinations Cloudflare Email Routing rules and Email Service documentation
Cloudflare Worker event handler and forwarding Cloudflare Email Routing / Workers documentation (follow current redirects or Email Service documentation if reorganized)
Postfix configuration and service parameters Postfix documentation, postconf(5), man postconf, man master, man postmap
Postfix Milter and header processing Postfix MILTER_README, header_checks(5), installed man header_checks
Dovecot 2.4.2 passwd-file Dovecot CE passwd-file database
Dovecot LMTP and Postfix Dovecot CE LMTP / Postfix how-to
Dovecot Sieve Dovecot CE Sieve plugin
TLS and Certbot Certbot user documentation, Cloudflare DNS plugin
Caddy HTTPS and PHP Automatic HTTPS, php_fastcgi, reverse_proxy
PHP-FPM PHP-FPM configuration manual
Roundcube releases and installation Official releases, installation guide, upgrade guide
SQLite online backup SQLite command-line interface, SQLite backup API
Fail2ban Official Fail2ban repository and docs, installed man jail.conf, man fail2ban-regex
DNSExit DNSExit website and account documentation
Rspamd installation Rspamd installation guide and first setup
Rspamd scores/actions Actions and scores, Understanding Rspamd
Rspamd Milter headers Milter headers module
Rclone Drive and headless setup Google Drive backend, Remote setup, rclone authorize
Restic repository and backup Preparing a repository, Restic documentation
Restic retention and pruning Removing backup snapshots
systemd timers and journald Installed man systemd.timer, man systemd.time, man journald.conf, systemd manuals
Log rotation Installed man logrotate, logrotate project
Gmail sender authentication Google email sender guidelines
Email and authentication standards SMTP RFC 5321, message format RFC 5322, IMAP4rev2 RFC 9051, SPF RFC 7208, DKIM RFC 6376, ARC RFC 8617, LMTP RFC 2033, Sieve RFC 5228

The official Dovecot 2.4.2, Roundcube release/installation, Cloudflare routing, Rspamd Milter/action, Rclone Drive and Restic repository/retention references were checked during preparation of this guide. Other links identify standard primary documentation for further use. In case a website moves or provider instructions change, prefer the installed man pages and current official project documentation. This runbook should be updated after any actual deployment change rather than treated as an immutable configuration source.


End of guide. The core reader Mail platform has demonstrated successful receiving, sending, authentication, Gmail duplication, spam filtering, local Junk sorting and remote encrypted backup snapshots. The remaining priority is proving routine recovery and maintenance, and completing and verifying the two requested independent mailboxes if not already done.