Day 2 · DNS, mail servers & hosting

Build a mail server with Postfix and Dovecot, and should you?

lesson 06 / 1917 min1 labpublished
Course contents
On this page
  1. The pieces
  2. main.cf: the lab server, line by line
  3. master.cf: the services
  4. Delivering with LMTP into Dovecot
  5. From lab to production
  6. Operating the queue
  7. The all-in-one route
  8. So, should you run your own?

Even if your organization uses Google Workspace or Microsoft 365, building a mail server once is the fastest way to understand what those services do for you. You have already used the lab server; this lesson opens it up: how its pieces fit together, what each setting does, how to turn it into a production-style server, how to operate its queue and logs, and, at the end, an honest answer to the question every admin asks at some point: should we run our own?

The pieces

A complete self-hosted mail server is a handful of programs, each doing one job:

JobCommon choiceAlternatives
SMTP: receive (port 25), accept submissions (587/465), send and queuePostfixExim, OpenSMTPD, Sendmail
IMAP and POP3, mailbox storage, user authenticationDovecotCyrus IMAP
Final delivery into mailboxes (LMTP), server-side filters (Sieve)Dovecot LMTP + PigeonholePostfix’s own local delivery
Spam and virus filtering, DKIM signing and checkingRspamd (one tool for all of it)SpamAssassin + OpenDKIM + OpenDMARC, ClamAV for viruses
TLS certificatesLet’s Encrypt with certbot or acme.shAny CA
WebmailRoundcube, SnappyMail
Users and domainsSystem users, or a SQL/LDAP database of virtual users

Postfix itself is not one program but a set of small daemons, each with as little privilege as possible, managed by master. You saw them in the logs: smtpd receives mail, cleanup normalizes it and assigns the queue ID, qmgr manages the queue, smtp delivers to other servers, lmtp and local deliver locally, bounce writes bounce messages. This design is why Postfix has an excellent security record.

main.cf: the lab server, line by line

postconf -n prints every setting that differs from the defaults. After this lesson’s changes (below), the lab server looks like this:

postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
compatibility_level = 3.6
disable_vrfy_command = yes
home_mailbox = Maildir/
inet_interfaces = loopback-only
inet_protocols = ipv4
mailbox_size_limit = 0
mailbox_transport = lmtp:unix:private/dovecot-lmtp
maillog_file = /var/log/postfix.log
message_size_limit = 26214400
mydestination = $myhostname, $mydomain, localhost
mydomain = example.com
myhostname = mail.example.com
mynetworks = 127.0.0.1/32
myorigin = $mydomain
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_CApath = /etc/ssl/certs
smtp_tls_security_level = may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP
smtpd_helo_required = yes
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_path = private/auth
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/ssl/lab/mail.crt
smtpd_tls_key_file = /etc/ssl/lab/mail.key
smtpd_tls_security_level = may
transport_maps = hash:/etc/postfix/transport

Grouped by purpose (a setting that starts with smtpd_ is about receiving, one that starts with smtp_ is about sending):

  • Identity. myhostname is the server’s name: it appears in the banner, in EHLO when sending, and in Received headers. It must match the server’s PTR record. mydomain and myorigin set the domain added to bare local names.
  • Which mail is ours. mydestination lists the domains delivered locally; mail for anything else is relayed. For many domains with users that aren’t system accounts, you’d use virtual_mailbox_domains and virtual_mailbox_maps instead, usually backed by SQL.
  • Who may relay. mynetworks lists trusted client IPs, and smtpd_relay_restrictions says: relay for trusted networks and logged-in users, and refuse everyone else for foreign domains (defer_unauth_destination, a 454; the stricter reject_unauth_destination gives a 554). This one line is what keeps the server from being an open relay.
  • Where it listens. inet_interfaces (all interfaces on a real server; loopback in the lab) and inet_protocols.
  • TLS. smtpd_tls_* is the certificate for receiving, with security_level = may (offer STARTTLS on port 25, don’t require it); smtp_tls_security_level = may makes Postfix use TLS when sending whenever the other side offers it; smtpd_tls_auth_only refuses AUTH outside TLS.
  • Authentication. smtpd_sasl_type = dovecot and smtpd_sasl_path hand password checks to Dovecot through a socket, so users have one password for IMAP and SMTP.
  • Delivery. mailbox_transport = lmtp:unix:private/dovecot-lmtp hands local mail to Dovecot over LMTP (below). recipient_delimiter = + enables alice+tag@ addresses.
  • Hygiene. disable_vrfy_command stops address harvesting with VRFY; smtpd_helo_required refuses clients that skip EHLO; message_size_limit is 25 MB here.
  • Routing. relayhost (empty: deliver directly to each domain’s MX; set it to send everything through a smarthost such as an ESP) and transport_maps for per-domain exceptions, which the lab uses to send example.net to the fake MX.

postconf -d prints every default, postconf parameter prints one value, postconf -e changes one, and man 5 postconf documents all of them. After editing, postfix check and then postfix reload.

master.cf: the services

master.cf lists the services master runs: one line per daemon, with options that override main.cf for that service only. The lab adds two services for submission:

submission inet n       -       y       -       -       smtpd
    -o syslog_name=postfix/submission
    -o smtpd_tls_security_level=encrypt
    -o smtpd_sasl_auth_enable=yes
    -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
    -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
submissions inet n       -       y       -       -       smtpd
    -o syslog_name=postfix/submissions
    -o smtpd_tls_wrappermode=yes
    ...

Port 587 (submission) is the same smtpd program as port 25, but with TLS required (encrypt), authentication on, and every client that hasn’t logged in refused. Port 465 (submissions) adds smtpd_tls_wrappermode, which means TLS from the first byte. Port 25 stays open to the world for incoming mail, with AUTH off. Keeping these roles separate is a basic rule: never allow user logins on port 25, and never accept unauthenticated mail on 587/465.

Delivering with LMTP into Dovecot

Out of the box, Postfix’s local daemon writes mail straight into each user’s ~/Maildir. That works, but production servers hand the last step to the IMAP server, so that Dovecot keeps its indexes up to date, applies Sieve filters and enforces quotas. Switch the lab server to LMTP:

# /etc/dovecot/local.conf: add lmtp to the protocols, and a socket inside Postfix's chroot
protocols = imap pop3 lmtp
service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    mode = 0600
    user = postfix
    group = postfix
  }
}
auth_username_format = %Ln
sudo apt install -y dovecot-lmtpd
sudo postconf -e "mailbox_transport = lmtp:unix:private/dovecot-lmtp" \
  "disable_vrfy_command = yes" "smtpd_helo_required = yes" "smtp_tls_security_level = may" \
  "smtpd_tls_auth_only = yes" "message_size_limit = 26214400"
sudo systemctl restart dovecot && sudo postfix reload

Send a test and look at both logs:

swaks --server 127.0.0.1:587 --tls --auth PLAIN --auth-user bob --auth-password bob-lab-pass \
  --from bob@example.com --to alice@example.com --header "Subject: Delivered over LMTP" --body hi --silent 2
grep lmtp /var/log/postfix.log | tail -2
tail -2 /var/log/dovecot.log
Nov 01 12:37:03 mail postfix/local[7447]: 7B0F78A2CB: passing <alice@example.com> to transport=lmtp
Nov 01 12:37:03 mail postfix/lmtp[7449]: 7B0F78A2CB: to=<alice@example.com>, relay=mail.example.com[private/dovecot-lmtp], delay=0.03, delays=0.01/0/0.01/0, dsn=2.0.0, status=sent (250 2.0.0 <alice@example.com> 96s/H28y52oaHQAAg+zDdQ Saved)
Nov 01 12:37:03 lmtp(alice)<7450><96s/H28y52oaHQAAg+zDdQ>: Info: msgid=<20261101123703.007439@vm>: saved mail to INBOX
Nov 01 12:37:03 lmtp(7450): Info: Disconnect from local: Logged out (state=READY)

Postfix’s log shows the handover with Dovecot’s 250 ... Saved reply, and Dovecot’s log shows the same message (same session ID) saved to Alice’s INBOX. When a user says a message never arrived, these two lines are the proof of delivery, and the Message-ID connects them to what the sender sees.

From lab to production

The lab server is deliberately minimal. A server on the Internet needs more:

The basics. A static public IPv4 address with a clean history (check it on the blocklists before you commit to it), port 25 open in both directions, a PTR record matching myhostname, and inet_interfaces = all. Many cloud providers block port 25 for new accounts and only unblock it on request, if at all.

Real TLS. A certificate from Let’s Encrypt for mail.example.com, renewed automatically, with a deploy hook that reloads Postfix and Dovecot. Require TLS 1.2 or newer where TLS is mandatory (submission, IMAP):

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_mandatory_protocols = >=TLSv1.2

On port 25, leave TLS opportunistic with Postfix’s default protocols: an old sending server that can only do TLS 1.0 should still get encryption rather than plaintext.

Checks on incoming mail, cheapest first, so most junk is refused before any expensive filtering:

smtpd_helo_restrictions = reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname
smtpd_sender_restrictions = reject_non_fqdn_sender, reject_unknown_sender_domain
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_recipient_restrictions = reject_non_fqdn_recipient, reject_unknown_recipient_domain,
    reject_rbl_client zen.spamhaus.org=127.0.0.[2..11]
  • postscreen, Postfix’s front door on port 25, checks each new connection before smtpd sees it: is the IP on DNS blocklists, does the client talk before the server greets it (spambots do), does it pipeline illegally. It removes most botnet traffic at almost no cost.
  • DNS blocklists such as Spamhaus ZEN. Spamhaus refuses queries that come through big public resolvers (8.8.8.8, 1.1.1.1), answering with error codes instead; run a local resolver such as Unbound on the mail server, and filter the answers to real listings as above.
  • Rspamd as a milter (smtpd_milters = inet:127.0.0.1:11332) scores content, checks SPF, DKIM and DMARC, and DKIM-signs outgoing mail, all in one daemon with a web interface.
  • ClamAV for attachments, also through Rspamd.

Abuse protection. fail2ban (or Postfix’s own anvil limits) against password guessing on submission and IMAP, which starts within minutes of a server going online. Rate limits per user, so one compromised account can’t send a hundred thousand messages before you notice.

Operations. Backups of /var/mail or the Maildirs and of the configuration, monitoring of the queue size and the disk, alerts on certificate expiry and on blocklist listings, log retention for investigations, and security updates applied promptly.

Operating the queue

These commands answer most “where is my email?” questions on a Postfix server:

CommandWhat it does
postqueue -p (or mailq)List the queue: queue ID, size, time, sender, recipients, and the last error for deferred mail
postqueue -fRetry all deferred mail now
postqueue -i QUEUEIDRetry one message now
postcat -vq QUEUEIDShow a queued message’s envelope, headers and body
postsuper -d QUEUEIDDelete one message (-d ALL deferred for all deferred mail; careful)
postsuper -h QUEUEID / -HPut a message on hold / release it
qshape deferredWhich destination domains the deferred mail is stuck on, by age
grep QUEUEID /var/log/mail.logThe whole life of one message

A queue that keeps growing means one of three things: a destination is refusing or rate-limiting you (look at the errors with postqueue -p), your own DNS or network is broken, or an account is sending spam. The third is an incident: hold the queue, find the account, reset its password, and delete the junk before it destroys your IP’s reputation.

The all-in-one route

Assembling and maintaining all of this by hand is a real job. Several projects package a complete, sensible server, usually with Docker and a web admin:

  • Mailcow: Postfix, Dovecot, Rspamd, SOGo webmail, in Docker, with a polished admin interface.
  • Mail-in-a-Box: turns one fresh Ubuntu server into a complete mail server, DNS included.
  • docker-mailserver: a single container configured with files, popular for small setups.
  • Stalwart: one modern program written in Rust that does SMTP, IMAP, JMAP and spam filtering.
  • Mox: one program in Go, aimed at being simple to run.

They save weeks of work, but you still own everything the next section describes.

So, should you run your own?

Self-hosting makes sense when…A hosted service makes sense when…
You have legal or data-residency rules that rule out the big providersYou want email to be someone else’s 24/7 problem
You need very high volumes or unusual routing at low costYour team doesn’t have a mail specialist
You run an ISP, a hosting company or an email productYou need calendars, Office documents and identity management integrated
You want to learn email in depth (do it at least once!)Deliverability to Gmail and Outlook has to be reliable from day one

The hidden costs of self-hosting are almost never the software. They are the reputation of your IP address (a new IP has none, and getting into Gmail and Outlook inboxes from it takes weeks of careful sending), port 25 policies of your provider, spam filtering that is as good as the big providers’ (hard), security patching and monitoring, backups, and being on call when the server fails at 3 a.m. Many organizations end up with a hybrid: hosted mailboxes for people, and their own Postfix only as an internal relay for applications and devices, forwarding through an ESP.