Why I Did This at All

For a long time, a forwarding service handled the email of my domain. Mail to my address arrived there. The service relayed it to the inbox of a big provider, and my replies came from that provider. It worked. But my primary identity on the internet (my email address) lived in someone else’s account. And it was awkward to send mail as my own domain.

I wanted the opposite. I wanted my own server, my own mailboxes and my own address on everything. I also wanted mail flow good enough that my messages arrive in inboxes and not in spam.

People say that email is the hardest thing to self-host, and some of that reputation is earned. But most of the difficulty is not the mail server. It is the network around the server, and the DNS records that prove you are legitimate. This post covers all of it, in the order I built it.

Choosing Mox

I chose Mox because it is a modern, all-in-one mail server written in Go:

  • One binary for SMTP, IMAP, webmail and an admin interface.
  • The modern mail security stack built in: SPF, DKIM, DMARC, MTA-STS, TLS reporting and DANE support. Mox makes the DKIM keys for you.
  • Its own certificates through ACME (Let’s Encrypt).
  • A quickstart that writes the config and prints every DNS record you need.

I accepted one trade-off. Mox has no LDAP or OpenID Connect, so it cannot use my single sign-on. Mail accounts have their own passwords. For a handful of mailboxes, that is fine.

The Problem Nobody Mentions First: Port 25

Mail servers talk to each other on TCP port 25. Almost every residential ISP blocks outbound port 25, and so do many cloud providers. Mine were no exception. My home connection blocks it, and so do two of my three cloud nodes.

Even with port 25 open at home, it is a bad idea to send from a residential IP. Residential ranges are on blocklists by default. Also, you usually cannot set the reverse DNS (PTR) record that receiving servers check.

So the design became this:

  • The mail server lives at home, in a container on Nayru (one of my Proxmox nodes). The mailboxes, the data and the backups are all on my hardware.
  • A small cloud node, Dinraal, is the edge. Its provider allows port 25, and its IP is not on blocklists. I can also set its PTR record.
  • All mail traffic, in both directions, goes through the edge. The internet only sees the IP of the edge.
            INBOUND                                             OUTBOUND
internet --> edge VPS (public IP, port 25/465/587/993)    mail server at home
                 |  DNAT                                       |  default route = edge (exit node)
                 v                                             v
         WireGuard tunnel (rides my private mesh)        edge VPS --> internet
                 |                                       (mail leaves from the edge IP,
                 v                                        which matches SPF and PTR)
         mail server at home (sees the REAL client IP)

Step 1: The Container and Mox

The container is small: Debian, 2 cores, 1.5 GB of RAM, 10 GB of disk. It needs access to /dev/net/tun for the tunnel. I built Mox from source and ran its quickstart as an unprivileged user:

go install github.com/mjl-/mox@latest
cd /home/mox && ./mox quickstart [email protected]

The quickstart writes two config files: mox.conf for the server and domains.conf for domains and accounts. It also prints every DNS record to add. Save that output in a private place, because it has the first admin and account passwords.

I changed two settings at once:

  • The admin web interface listens only on localhost. I never expose it, not even on my LAN.
  • Catch-all addresses. Mail to anything at my domain goes to my mailbox. In Mox, an address that starts with @ is a catch-all:
./mox config address add @example.com myaccount

Step 2: A DNSSEC-Validating Resolver

Mox wants a resolver that validates DNSSEC. It uses DNSSEC for DANE and to trust the records it looks up. The DNS servers on my LAN do not validate. My router also blocks plain DNS to the internet.

So the mail container runs its own Unbound. Unbound listens on localhost and forwards to public resolvers over DNS-over-TLS, with validation on. The resolver setting of the container points at 127.0.0.1.

This gave me one operational habit: after you change DNS records, restart Unbound. Unbound caches “this record doesn’t exist” answers. So Mox keeps believing that a record is missing long after you added it.

Step 3: The Inbound Path, With Real Client IPs

My private mesh (Tailscale) already connects the edge and the home container. The obvious idea is to forward port 25 on the edge to the mesh address of the container. That does not work. The packet filter of the mesh drops traffic whose source is not another mesh device, and mail comes from any IP on the internet.

The common workaround is NAT on the edge (masquerading). But then every connection seems to come from the edge itself. That ruins the per-IP throttling of the mail server, and it makes abuse detection useless.

My solution is a plain WireGuard tunnel between the edge and the container, carried over the mesh. It is a tiny point-to-point link with its own private addresses. Its MTU is 1200, to leave room for the double encapsulation.

On the edge, the mail ports are DNAT’d into the tunnel with no masquerading. So the original client IP stays the same:

# edge: public mail ports -> the mail server's tunnel address, source IP untouched
iptables -t nat -A PREROUTING -i <public-if> -p tcp -m multiport --dports 25,465,587,993 \
         -j DNAT --to-destination <mail-tunnel-ip>

The return path is the subtle part. The default route of the mail server is not this tunnel. So replies to an internet client would leave the wrong way, and the client would never see them. The container marks connections that came in through the tunnel. Then it routes their replies back the same way:

# mail container (simplified): remember connections that came in via the tunnel ...
nft add rule inet mailtun prerouting iifname "wgmail" ct mark set 0x99
# ... and send their replies back through it
nft add rule inet mailtun output ct mark 0x99 meta mark set 0x99
ip rule add fwmark 0x99 lookup 199
ip route add default dev wgmail table 199

Two more details:

  • Bind Mox to explicit addresses. I listed the LAN address and the tunnel address of the container. 0.0.0.0 did not cover the tunnel interface correctly.
  • Start Mox after the tunnel. A systemd drop-in makes Mox wait for the WireGuard interface.

Mox does not support the PROXY protocol, which is the other usual way to pass client IPs through a proxy. That is why I do this at the network layer.

Step 4: Port 443 on a Shared Edge

The edge also serves the origin of my blog on 443. Mox needs 443 for two things. The first is its own ACME certificates (the TLS-ALPN challenge). The second is the MTA-STS policy and the autoconfig hostnames.

I solved it with an nginx stream SNI split on the edge. It routes TLS connections by hostname before it decrypts anything:

  • mail., mta-sts. and autoconfig. hostnames → the mail server (through the tunnel)
  • the blog’s hostnames → the local web server, only from my CDN’s IP ranges
  • anything else → refused

I learned a lesson about order here. I let Mox request its certificate before I routed port 443 to it. The challenge failed several times, and Let’s Encrypt rate-limited the hostname for an hour. Make the path work first. Then let ACME run.

There is also a classic hairpin problem. From inside, the mail container cannot reach the public IP of the edge. So a lookup of its own hostname went nowhere. I fixed it with a one-line /etc/hosts entry inside the container. It points the mail hostname at the tunnel address.

Step 5: The Outbound Path

Outbound is simpler. The mail container is a member of my mesh and uses the edge as its exit node. So everything it sends leaves for the internet from the IP of the edge. That includes SMTP to other mail servers.

This one choice keeps my mail reputation simple. One IP address sends my mail. SPF names that address. My mail hostname points to it, and its PTR record points back to the hostname.

Step 6: DNS, Record by Record

This is where you win or lose mail flow. Every record below has a job.

RecordExampleWhy it exists
A for the mail hostmail.example.com → <edge IP> (not proxied by the CDN)where other servers connect
MXexample.com MX 10 mail.example.com“send mail for this domain here”
SPF (domain)v=spf1 ip4:<edge IP> mx ~allwhich IPs may send as the domain
SPF (mail host)mail.example.com: v=spf1 a -allcovers the server’s own hostname in SMTP greetings and bounces
DKIM (two selectors)2026a._domainkey, 2026b._domainkeycryptographic signature on every outgoing message; the second key makes rotation painless
DMARCv=DMARC1; p=quarantine; rua=mailto:[email protected]tells receivers what to do when SPF/DKIM don’t align, and sends you reports
MTA-STS_mta-sts TXT + a policy served on mta-sts. (mode enforce)forces other servers to use valid TLS when delivering to you
TLS reporting_smtp._tls TXTreports from other servers about TLS problems delivering to you
SRV / autoconfig_imaps._tcp, _submissions._tcp, autoconfig/autodiscovermail apps configure themselves from an address and password
PTR (set at the VPS provider)<edge IP> → mail.example.comreverse DNS that matches forward DNS (“FCrDNS”), checked by almost every receiver

Some notes from experience:

  • Start DMARC at quarantine, not reject. It still protects your domain from spoofing. But it gives you room while you confirm that everything aligns. Read the reports.
  • The MX host must not be behind the proxy of your CDN. CDNs proxy HTTP, not SMTP.
  • Don’t add a CAA record if your CDN gets certificates for your website from a different authority. A CAA record that listed only Let’s Encrypt broke nothing for mail. But it would have broken the edge certificates of my CDN for the site. Check before you add one.
  • Ask your VPS provider for the PTR record. It is often a field in the control panel. It is the biggest deliverability factor that you do not control in DNS.

Mox can check all of this itself:

./mox config dnsrecords example.com    # what it expects
./mox config dnscheck example.com      # what the world actually serves

Step 7: The Cut-Over

The move from a forwarding service to your own MX is mostly DNS. There is one trap: when you turn off the forwarding service, it can delete DNS records that it manages. When I disabled mine, it removed its MX records and the root SPF record. As soon as you disable it, add your MX and SPF again. Then check them at once.

Then test both directions with a big free mailbox provider:

  • Outbound: send from Mox to an external mailbox. Make sure it lands in the inbox, not spam. Open the headers. SPF, DKIM and DMARC must all show pass.
  • Inbound: reply from the external mailbox. For that connection, the mail server log must show the real IP of the sender, not the edge IP. That tells you that the tunnel and the DNAT do their job.

Step 8: Hardening and Visibility

The server sees real client IPs, so the per-IP throttling of Mox works as designed. I also wrote a small sentry. It checks the logs every five minutes and sends me a push notification for:

  • 5 or more failed logins from an address that is not mine (urgent at 20 or more),
  • a successful login from an IP I have never seen before,
  • outbound volume that is unusually high (a compromised account is the classic reason a mail server gets on a blacklist),
  • an outgoing queue that grows.

Each alert fires at most once every six hours, so a scanner cannot spam my phone. The review of the first day showed what you expect from a public mail server. There were internet-wide scanners and one probe without credentials. There were no relay attempts, and nothing was in the queue.

The same script writes a status file. That file feeds a Mail section on my homelab dashboard. It shows service and tunnel health, certificate expiry and queue size. It also shows 24-hour counts of received, sent, rejected and failed logins. I also gave my external port-audit job the legitimate mail ports of the edge, so it no longer flags them as unexpected.

Step 9: Real IPs for Webmail, Too

Steps 3 and 4 gave SMTP and IMAP the real client IPs. But webmail still came in over the 443 passthrough. So every webmail visitor seemed to come from the tunnel. That made the webmail throttling of Mox global in practice. One person who hammered the login page could slow it down for everyone.

The fix was to stop passing webmail through as raw TLS. Now the edge terminates it:

  1. The edge gets a copy of the Mox certificate. A daily job on the mail server splits the ACME cache of Mox into certificate and key. It copies them to the edge over the mesh with a key that can write only to that one folder. A watcher on the edge validates the nginx config and reloads it.
  2. The SNI split now uses the PROXY protocol internally. It also looks at ALPN. ACME’s acme-tls/1 handshakes still go straight to Mox, so Mox can renew its own certificates. Normal webmail TLS terminates on the edge.
  3. Nginx proxies webmail to a plain-HTTP Mox listener through the tunnel, with a Forwarded / X-Forwarded-For header. Mox trusts that header on that listener only.

Now Mox logs a bad webmail login with the real IP of the attacker. Mox throttles only that attacker.

The first attempt taught me a lesson.

I tried to add a simple connection limit to the nginx stream block, with the SNI hostname as the key. In nginx, limit_conn runs before ssl_preread. So the hostname was still empty when nginx evaluated the limit. The routing map cached that empty value, and every mail connection fell through to “refuse”. Webmail was down for two minutes before I reverted it. In the stream module of nginx, the order of operations matters.

What Broke Later (and What It Taught Me)

A week of silently blocked inbound mail

Four days after the build, inbound mail stopped arriving. I did not notice for a week.

On the edge, a separate script protects my Docker containers. It builds a firewall chain again from scratch each time Docker restarts. My mail forwarding depended on a rule in that chain. When Docker restarted, the script built the chain without my rule. The final DROP of the chain quietly ate all inbound mail.

The fix was to make the mail forwarding apply itself again each time that guard script runs. The bigger lesson was about monitoring. I watched that the mail server was up, but not that mail was arriving. A server can be perfectly healthy while nothing reaches it. Check the path, not only the process.

A routing loop inside a tunnel inside a tunnel

Later, the CPU of the edge started to spike to 100%. The tunnel had moved over a terabyte of traffic.

The cause was elegant in a terrible way. Tailscale found that it could reach the mail server through the address of the WireGuard tunnel. But that tunnel itself rides on Tailscale. About every 75 seconds, Tailscale switched onto that path. So packets went Tailscale → WireGuard → Tailscale → … in a loop.

The fix is a small firewall rule on both ends. It drops Tailscale’s own traffic if that traffic tries to leave through the mail tunnel. Tailscale marks its packets, so they are easy to identify. The general lesson: when you nest tunnels, make sure that the outer one can never find a path through the inner one.

Adding a Second Domain

Two weeks later, I wanted mail on a second domain (the one this blog lives on), with the same catch-all. The edge, the tunnel and the certificates were already in place, so it took minutes:

./mox config domain add example.org myaccount     # new domain + its own DKIM keys
./mox config address add @example.org myaccount   # catch-all

Then I added the DNS records for the new domain. The MX points at the existing mail hostname. There are the two DKIM keys, SPF, DMARC at quarantine and TLS reporting. For now, I skipped MTA-STS and the client autoconfig records on purpose. Nobody logs in as that domain, and the SNI split on the edge routes only the mail hostnames of the first domain.

I tested acceptance with a plain SMTP conversation through the edge. RCPT TO for the new address answered 250. Then I sent real mail both ways.

One false alarm is worth knowing about. mox config dnscheck reported an SPF “fail” for the mail host on both domains. The hairpin /etc/hosts entry causes it. The check resolves the mail hostname to the tunnel address, not the public one. Real receivers see the public record, and mail passes SPF. Know which of your own workarounds can fool your own tools.

Takeaways

  • Port 25 decides your architecture. Keep the mailboxes at home. Put a small, reputable cloud node at the edge for both inbound and outbound.
  • Keep the real client IPs. DNAT into a WireGuard tunnel (do not masquerade). Route replies back through it with connection marks. Without real IPs, throttling and abuse detection are blind.
  • Send from the IP your DNS describes. The edge IP must match SPF, the A record of the mail host and the PTR record.
  • Treat DNS as the product. You need MX, SPF for the domain and the host, two DKIM selectors and DMARC that starts at quarantine. You also need MTA-STS, TLS reporting and PTR. Let the mail server check them for you.
  • Run a DNSSEC-validating resolver next to the mail server. Restart it after DNS changes.
  • Get port 443 routing right before ACME runs. If you don’t, you will hit rate limits.
  • When you leave a forwarding service, add MX and SPF again at once. When you disable the service, it can remove them.
  • Monitor mail flow, not only the server. Mine was “up” for a week while nothing arrived.
  • Nested tunnels need guardrails, so the outer one can never route through the inner one.
  • It is absolutely doable, and your own address is worth it. Build the boring parts carefully.