Bookmarks

Mail server

A mail server built from Postfix, Dovecot and Rspamd for sending, receiving and storing mail. The reference covers DNS, IMAP, TLS, SPF, DKIM, DMARC and anti-spam.

checked 7 Nov · next check 14 Nov · 64 min read

Sections
14
Reading
64 min
Current version
3.11.7
Written from
postfix.org/documentation.html

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What a mail server is and how it works

A mail server is not one program but a set of roles described in RFC 5598: accepting messages from users, relaying them between servers, delivering them to a mailbox, and giving access to the mailbox over IMAP. In this reference, Postfix, Dovecot and Rspamd fill those roles.

Roles and programs

The mail user agent (MUA) is the user’s program: Thunderbird, a mobile app or a web interface. The server performs all the other roles.

RoleWhat it doesCovered in the stack by
Accepting mail from your own users (mail submission agent, MSA)accepts a message on ports 587 and 465 after the user logs inPostfix; Dovecot checks the login (SASL)
Relaying between servers (mail transfer agent, MTA)holds the queue, finds the recipient’s server and hands the message over by SMTP; accepts other servers’ mail on port 25Postfix
Delivery to a mailbox (mail delivery agent, MDA)receives the message from Postfix over LMTP and puts it in the mailboxDovecot
Storage and accessstores messages in Maildir format and serves them to clients over IMAPDovecot
Filterchecks SPF, DKIM and DMARC, scores spam, signs outgoing messages with DKIMRspamd, through the milter protocol

DNS and TLS are just as much a part of the system: DNS says where to deliver messages and whom to trust, and TLS encrypts the connections.

The path of a message from sender to mailbox

The client hands the message to its own server on port 587 or 465 and authenticates with a login. From there the server finds the recipient itself: the message waits in the queue while Postfix looks up the recipient domain’s MX record in DNS and connects to the server it names on port 25.

The MX lookup is dashed; Rspamd connects to Postfix as a milter.
  1. The client connects to port 587 or 465 of its server and logs in (MSA).
  2. Postfix accepts the message and puts it in the outgoing MTA queue.
  3. Postfix looks up the recipient domain’s MX record in DNS.
  4. It connects to the server it finds on port 25.
  5. The recipient’s Postfix passes the message to Rspamd: SPF, DKIM, DMARC and anti-spam.
  6. If the checks pass, Postfix hands the message to Dovecot over LMTP.
  7. Dovecot puts the message in Maildir.
  8. The recipient’s client collects the message over IMAP.

Envelope and message

SMTP transfers an object in two parts (RFC 5321): the envelope and the content. The envelope consists of the MAIL FROM (sender address) and RCPT TO (recipient address) commands, and the server uses them to decide where to deliver the message. The message is the headers and body defined by RFC 5322, including the From: and To: that a person sees. The two sets of addresses can differ, for example with mailing lists and blind copies. SPF and DMARC are built on this: SPF checks the envelope address, and DMARC compares the domain in From: with the domain that passed SPF (from the envelope) or DKIM.

The servers’ dialogue looks like this: each client command gets a reply with a three-digit code. 2xx means success, 3xx means go on, 4xx is a temporary error and 5xx is a permanent one. The codes are covered in the “Common errors and diagnostics” section.

textan SMTP dialogue, abridged
S: 220 mx.example.org ESMTP PostfixC: EHLO mail.example.comS: 250-mx.example.orgS: ...C: MAIL FROM:<anna@example.com>S: 250 2.1.0 OkC: RCPT TO:<bob@example.org>S: 250 2.1.5 OkC: DATAS: 354 End data with <CR><LF>.<CR><LF>C: From: Anna <anna@example.com>C: To: Bob <bob@example.org>C: Subject: HelloC:C: Hi, Bob!C: .S: 250 2.0.0 Ok: queued as 4F3A21BC: QUITS: 221 2.0.0 Bye

IMAP and POP3

A client reads messages over IMAP or POP3. IMAP keeps messages and folders on the server, so a phone and a computer see the same mailbox; POP3 downloads messages from the server. This reference sets up IMAP. IMAP cannot send mail: that is what ports 587 and 465 are for.

What you need for your own server

  • A domain with managed DNS: you must be able to create MX, TXT and PTR records.
  • A static public IP address with a PTR record, which your hosting provider issues.
  • Port 25 open in both directions.
  • Time to build the reputation of a new IP address: the first messages may land in spam (see the “Deliverability and reputation” section).

What to know beforehand

  • DNS: the “TCP/IP and DNS” reference, section “DNS records”.
  • TLS and certificates: the “TLS and PKI” reference.
  • Basic Linux and systemd: packages, services, logs.

Section sources

the section is written from these pages

Cheat sheet: ports, commands, files

Everyday ports, commands and files for Postfix, Dovecot and Rspamd. Replace the names in the examples (example.com, mail.example.com, ID) with your own. Details are in the sections on Postfix, Dovecot, anti-spam and diagnostics.

Ports

PortPurposeListener
25SMTP: receiving mail from other serversPostfix, public
587submission: mail from users, STARTTLSPostfix, public
465submissions: mail from users, TLS from the first bytePostfix, public
143IMAP, STARTTLSDovecot
993IMAPS: IMAP, TLS from the first byteDovecot, public
110, 995POP3 and POP3S, only if you need POP3Dovecot
11332milter: the link between Postfix and RspamdRspamd, 127.0.0.1 only
11334Rspamd web interfaceRspamd, local only

Postfix

TaskCommand
Show changed parameterspostconf -n
Show a parameter’s default valuepostconf -d myhostname
Write a parameter to main.cfpostconf -e 'myhostname = mail.example.com'
Show the services in master.cfpostconf -M
Check permissions and directoriespostfix check
Reload the configurationpostfix reload
List the queuepostqueue -p
Retry delivery of the whole queuepostqueue -f
Show a message in the queuepostcat -q ID
Delete a message from the queuepostsuper -d ID
Build a lookup table from a filepostmap /etc/postfix/vmailbox
Rebuild the alias databasenewaliases

Dovecot

TaskCommand
Show changed settingsdoveconf -n
Reload the configurationdoveadm reload
Check a login and passworddoveadm auth test user@example.com
Show what userdb knows about a userdoveadm user user@example.com
List a mailbox’s foldersdoveadm mailbox list -u user@example.com

Rspamd

TaskCommand
Check the configuration syntaxrspamadm configtest
Show the effective configurationrspamadm configdump
Create a DKIM keyrspamadm dkim_keygen -s mail -d example.com
Counters and statisticsrspamc stat
Train as spamrspamc learn_spam spam.eml
Train as hamrspamc learn_ham good.eml

Checking from outside

TaskCommand
A domain’s MX recordsdig MX example.com +short
Reverse (PTR) record for an IPdig -x 203.0.113.10 +short
DMARC recorddig TXT _dmarc.example.com +short
STARTTLS connection on 587openssl s_client -starttls smtp -connect mail.example.com:587
Test messageswaks --to user@example.com --server mail.example.com

Files and directories

FileContents
/etc/postfix/main.cfmain Postfix parameters
/etc/postfix/master.cfPostfix services: smtp, submission, submissions
/etc/dovecot/dovecot.confmain Dovecot configuration
/etc/rspamd/local.d/your own Rspamd settings; files in override.d/ replace the defaults entirely
/var/spool/postfix/Postfix queues
/var/lib/rspamd/dkim/private DKIM keys for signing outgoing messages
/var/log/mail.logthe mail log on Debian and Ubuntu; without rsyslog, use journalctl -u postfix

SMTP reply codes

CodeMeaningWhat the sender does
2xxsuccesstreats the command as done and continues
4xxtemporary errorkeeps the message in the queue and retries later
5xxpermanent errorstops trying and bounces the message to the sender

Section sources

the section is written from these pages

Installation and first start

On Debian and Ubuntu, Postfix, Dovecot and Rspamd are installed as apt packages. Rspamd needs Redis for its statistics, and you should use Dovecot 2.4, which Ubuntu 24.04 does not ship. Set the hostname before installing, then check the services and ports afterwards.

Hostname

The hostname ends up in the Postfix myhostname parameter, in the SMTP greeting and in the PTR record, so set it before installing. Here and below, mail.example.com and 203.0.113.10 are examples: use your own name and address. The PTR record is covered in the “DNS for mail: MX, PTR, SPF, DMARC, MTA-STS” section.

bashon the server
sudo hostnamectl set-hostname mail.example.com

Add a line with the public address and the full hostname to /etc/hosts:

text/etc/hosts
203.0.113.10 mail.example.com mail

Package versions

Distribution versions lag behind the projects’ releases. This reference covers Dovecot 2.4, whose configuration format differs from 2.3. An old configuration will not work in 2.4 without changes.

SystemPostfixDovecotRspamd
Debian 133.10.132.4.13.12.1
Ubuntu 24.043.8.62.3.213.8.1
Ubuntu 26.043.10.62.4.23.8.1

Project repositories

Dovecot publishes packages at repo.dovecot.org. Here is an example for Debian 13: the key and the source file. For Ubuntu 24.04, change the path in URIs to .../ubuntu/noble and Suites to noble; for 26.04, use resolute.

bashon the server, Debian 13
curl https://repo.dovecot.org/DOVECOT-REPO-GPG-2.4 \  | sudo gpg --dearmor -o /usr/share/keyrings/dovecot.gpgsudo tee /etc/apt/sources.list.d/dovecot.sources <<EOFTypes: debURIs: https://repo.dovecot.org/ce-2.4-latest/debian/trixieSuites: trixieComponents: mainSigned-By: /usr/share/keyrings/dovecot.gpgEOF

Rspamd uses the rspamd.com/apt-stable repository. The key goes in /etc/apt/keyrings, and signed-by in the source line points to it.

bashon the server
sudo apt install lsb-release wget gpgsudo mkdir -p /etc/apt/keyringswget -O- https://rspamd.com/apt-stable/gpg.key | gpg --dearmor \  | sudo tee /etc/apt/keyrings/rspamd.gpg > /dev/nullCODENAME=$(lsb_release -c -s)echo "deb [signed-by=/etc/apt/keyrings/rspamd.gpg] \http://rspamd.com/apt-stable/ $CODENAME main" \  | sudo tee /etc/apt/sources.list.d/rspamd.list

Installing the packages

bashon the server
sudo apt updatesudo apt install postfix dovecot-core dovecot-imapd \  dovecot-lmtpd postfix-lmdb redis-serversudo apt --no-install-recommends install rspamd

Postfix will ask debconf questions. Choose the Internet Site type and enter the system mail name, which is your domain, for example example.com. You can change the answers later with sudo dpkg-reconfigure postfix.

Redis for Rspamd

Rspamd keeps Bayes statistics, greylisting data and rate-limit counters in Redis. Installing Redis is not enough: the default configuration does not name a Redis server, so these features stay off until you add one. Without Redis, Rspamd runs but lacks them.

text/etc/rspamd/local.d/redis.conf
servers = "127.0.0.1";

Rspamd also needs a local recursive DNS resolver.

Starting and checking

bashon the server
sudo systemctl enable --now postfix dovecot rspamd \  redis-serverpostconf mail_versiondovecot --versionapt policy rspamdsudo ss -ltnp

Postfix listens on port 25, and Rspamd on port 11332 on 127.0.0.1, which is the milter endpoint. Dovecot opens ports 143 and 993 after configuration, because IMAPS needs a certificate (see the “TLS for SMTP and IMAP” and “Dovecot: IMAP, LMTP, SASL and Maildir” sections).

textexample output
LISTEN 0 100  0.0.0.0:25  0.0.0.0:*  users:(("master",pid=812,fd=13))LISTEN 0 4096 127.0.0.1:11332 0.0.0.0:* users:(("rspamd",pid=640,fd=9))...

Where things are

WhatWhere
Postfix configuration/etc/postfix/
Dovecot configuration/etc/dovecot/; in version 2.4, dovecot.conf starts with dovecot_config_version
Your own Rspamd settings/etc/rspamd/local.d/ and /etc/rspamd/override.d/; do not edit the files that ship with the package
Postfix log/var/log/mail.log or journalctl -u postfix
Rspamd log/var/log/rspamd/rspamd.log

The mail.log file appears if rsyslog is installed. Without it, read the log with journalctl; Postfix can also write to a file itself, which the maillog_file parameter enables.

Firewall ports

Open incoming ports 25, 465, 587 and 993. Firewall rules are covered in the “Linux server hardening” reference, section “Firewall”. Some hosting providers block outgoing port 25 by default: check this before configuring, or the server will not send a single message.

Section sources

the section is written from these pages

DNS for mail: MX, PTR, SPF, DMARC, MTA-STS

A mail domain needs three kinds of records: MX and the host address say where to send mail; PTR, SPF, DKIM and DMARC prove that a message came from you; MTA-STS and TLS-RPT require the channel to be encrypted. Without them, messages get lost or land in spam.

The sender reads the MX and MTA-STS records; the receiving server checks the rest.

Which records you need

An example for the domain example.com and the mail host mail.example.com. The addresses come from the documentation blocks 203.0.113.0/24 and 2001:db8::/32. The DKIM record is covered in the “DKIM signing in Rspamd” section.

RecordNameValue
MXexample.com10 mail.example.com.
Amail.example.com203.0.113.25
AAAAmail.example.com2001:db8::25
PTR25.113.0.203.in-addr.arpamail.example.com.
TXT (SPF)example.comv=spf1 mx -all
TXT (SPF for HELO)mail.example.comv=spf1 a -all
TXT (DMARC)_dmarc.example.comv=DMARC1; p=none; rua=mailto:dmarc@example.com
A (policy host)mta-sts.example.com203.0.113.80
TXT (MTA-STS)_mta-sts.example.comv=STSv1; id=20261107000000Z
TXT (TLS-RPT)_smtp._tls.example.comv=TLSRPTv1; rua=mailto:tlsrpt@example.com

Record format, CNAME and TTL are covered in the “TCP/IP and DNS” reference, section “DNS records”.

MX and the host address

An MX (mail exchanger) record names the server that accepts the domain’s mail. The number before the name is the priority: the sender tries the lower value first and moves to a higher one if it is unreachable. MX must point to a name that has an A or AAAA record, not to an IP address.

textthe example.com zone
example.com.       3600 IN MX   10 mail.example.com.mail.example.com.  3600 IN A    203.0.113.25mail.example.com.  3600 IN AAAA 2001:db8::25

PTR: the name for an address

PTR (pointer) is a reverse record: given the server’s IP address, it returns the server’s name. You need forward-confirmed reverse DNS: the address’s PTR points to mail.example.com, and that name’s A record points back to the same address. The PTR record is created by the owner of the address, usually the hosting provider, in its control panel. The name in the Postfix myhostname must match the PTR: smtp_helo_name defaults to $myhostname, and that is the name the server gives in its EHLO greeting.

bashon the host
dig +short -x 203.0.113.25dig +short A mail.example.com

SPF: who may send on behalf of the domain

SPF (Sender Policy Framework, RFC 7208) is a TXT record listing the hosts allowed to send mail on behalf of the domain. The recipient checks two names: the one from MAIL FROM and the one from the HELO greeting. That is why you need a record for both the domain and the hostname. The record v=spf1 mx -all allows the servers in the domain’s MX and forbids all others.

ElementMeaning
mx, aaddresses from the domain’s MX or A records
ip4:, ip6:an address or network, for example ip4:203.0.113.0/24
include:another domain’s rules, for example a mailing service’s
-alleverything else is rejected (fail)
~alleverything else is a soft fail (softfail), for testing

DMARC: what to do when a check fails

DMARC (RFC 9989, which replaced RFC 7489) is published as a TXT record at _dmarc.example.com. It compares the domain in the From: header with the domain that passed SPF or DKIM, which is called alignment. If neither matches, the recipient applies the policy from the p tag. One aligned mechanism out of the two is enough for a message to pass.

TagWhat it setsDefault
vthe version, DMARC1, first in the recordrequired
pthe policy: none, quarantine, rejectnone
sp, npthe policy for subdomains and for non-existent subdomainsthe value of p
adkim, aspfalignment: r is relaxed, s is strictr
ruawhere to send aggregate reports, mailto:no reports
ty is testing mode: the policy is applied one level softern

RFC 9989 removed the pct tag (the registry marks it as historic): the t tag replaced applying the policy to a share of messages. The recipient finds the organisational domain by walking the DNS tree (DNS Tree Walk, at most eight queries) rather than from the public suffix list.

Roll the policy out based on the reports:

  1. Start with p=none and rua: mail is not affected, and the reports show who sends on your behalf.
  2. Once the legitimate sources pass SPF or DKIM, move to p=quarantine, optionally starting with t=y.
  3. Then switch on p=reject.

MTA-STS and TLS-RPT: encryption on demand

MTA-STS (RFC 8461) tells senders that the domain’s mail must be delivered only over TLS to the listed servers. The policy is flagged by the TXT record _mta-sts.example.com, and the policy itself is the file https://mta-sts.example.com/.well-known/mta-sts.txt, served over HTTPS by the mta-sts host. Change the id field whenever the policy changes, or senders will keep the old one cached.

textthe mta-sts.txt file
version: STSv1mode: testingmx: mail.example.commax_age: 86400

The testing mode only reports TLS failures, enforce forbids delivery without verified TLS, and none switches the policy off. max_age is the cache lifetime in seconds, at most 31557600; for enforce, use weeks. For how Postfix itself checks other domains against MTA-STS, see the “TLS for SMTP and IMAP” section.

TLS-RPT (RFC 8460) is the record _smtp._tls.example.com with a rua address: senders send reports there about TLS failures when delivering to you. A report is JSON with the number of successful and failed sessions and the reason for each failure.

Publishing order and verification

Resolver caches keep old records until the TTL expires. A day before a move, lower the TTL to 300 seconds, then publish. The order is: A, AAAA, MX and PTR; SPF; DKIM; DMARC with p=none; MTA-STS in testing mode. To check all the records:

bashon the host
dig +short MX example.comfor n in example.com _dmarc.example.com \         _mta-sts.example.com _smtp._tls.example.com; do  dig +short TXT "$n"done

Section sources

the section is written from these pages

Configuring Postfix: main.cf and master.cf

Postfix is configured with two files: main.cf holds parameters in the form name = value, and master.cf holds services and ports. Change parameters with postconf -e, validate with postfix check, and apply with postfix reload.

Two commands to edit, one to check

bashon the host
sudo postconf -e 'myhostname = mail.example.com'sudo postfix checksudo postfix reload

postconf -n prints only the parameters you have changed, and postconf -d prints the default values. Change master.cf services by editing the file and running the same postfix reload. The inet_interfaces parameter takes effect only after a full Postfix restart.

Main main.cf parameters

ParameterWhat it setsDefault
myhostnamethe full host name, mail.example.comthe name from gethostname()
mydomainthe domain of the mail systemmyhostname without its first label
myoriginthe domain in the addresses of locally posted mail$myhostname
mydestinationdomains whose mail is delivered locally$myhostname, localhost.$mydomain, localhost
mynetworkstrusted networks allowed to relayderived from mynetworks_style
inet_interfacesinterfaces on which mail is acceptedall
inet_protocolsipv4, ipv6 or bothdepends on the build
relayhostthe host that receives all outbound mailempty
message_size_limitthe largest message size in bytes10240000

A minimal main.cf for a server with virtual domains: the public domain is not in mydestination but in virtual_mailbox_domains (see “Virtual domains and mailboxes”).

inimain.cf
myhostname = mail.example.commydomain = example.commyorigin = $mydomainmydestination = $myhostname, localhost.$mydomain, localhostmynetworks = 127.0.0.0/8 [::1]/128inet_protocols = allmessage_size_limit = 26214400

Ports and services in master.cf

Port 25 accepts mail from other servers. Users send their mail to port 587 (submission, RFC 6409; STARTTLS and authentication are required) or to 465 (submissions, RFC 8314; TLS from the first byte). For 465, enable smtpd_tls_wrappermode=yes, but only as a -o option of the service, not in main.cf. For certificates and the SASL type, see “TLS for SMTP and IMAP” and “Dovecot: IMAP, LMTP, SASL and Maildir”.

textmaster.cf
smtp        inet  n  -  n  -  -  smtpdsubmission  inet  n  -  n  -  -  smtpd  -o syslog_name=postfix/submission  -o smtpd_tls_security_level=encrypt  -o smtpd_sasl_auth_enable=yes  -o smtpd_relay_restrictions=permit_sasl_authenticated,rejectsubmissions inet  n  -  n  -  -  smtpd  -o syslog_name=postfix/submissions  -o smtpd_tls_wrappermode=yes  -o smtpd_sasl_auth_enable=yes  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject

A hyphen in a column means the default value. A line with -o continues the service above it: it starts with whitespace and overrides a parameter for that service only.

Aliases and address extensions

The /etc/aliases file redirects mail for local recipients by the part of the address before the @. After editing it, rebuild the database with newaliases. The recipient_delimiter = + parameter enables extensions: for user+news@example.com, Postfix first looks up the address with the extension, then user@example.com.

text/etc/aliases
postmaster: rootroot: admin@example.com

How the queue works

A message enters through smtpd (or pickup, if it was sent locally), passes through cleanup and lands in the incoming directory. The queue manager qmgr moves it to active and starts delivery with the smtp or lmtp agent. The active queue lives mostly in memory and by default holds up to 20,000 messages.

A message does not leave hold on its own until an administrator steps in (postsuper -h puts it there, -H releases it).

Deferred messages go back for another attempt. The queue is scanned every queue_run_delay, and Postfix doubles the pause between attempts according to the age of the message, within two limits.

ParameterDefaultWhat it sets
queue_run_delay300show often deferred is scanned
minimal_backoff_time300sthe shortest pause between attempts
maximal_backoff_time4000sthe longest pause between attempts
maximal_queue_lifetime5dhow long a message stays in the queue before it is bounced
bounce_queue_lifetime5dthe same for bounce messages themselves
bashon the host
postqueue -psudo qshape deferred

Connecting Rspamd as a milter

A milter is an external filter that Postfix calls during the SMTP session. Rspamd listens on port 11332. For checks and training, see “Spam filtering in Rspamd: checks and training”.

inimain.cf
smtpd_milters = inet:127.0.0.1:11332non_smtpd_milters = $smtpd_miltersmilter_default_action = accept

Tables and compatibility_level

For tables such as lmdb:/etc/postfix/vmailbox, build the index with postmap. postconf -m lists the supported types; on Debian and Ubuntu, lmdb support is a separate package, postfix-lmdb. The default type is set by default_database_type, which on many systems is lmdb or hash. Postfix picks up a new index after about a minute; postfix reload speeds this up.

The compatibility_level parameter is a safety net for upgrades: while it is lower than the built-in value, Postfix keeps the old defaults and logs Using backwards-compatible default setting .... Review those lines, pin the values you need in main.cf, and run postconf compatibility_level=N, where N is the number from the warning.

Section sources

the section is written from these pages

Virtual domains and mailboxes

Virtual domains (hosted domains) are domains for which Postfix accepts mail but whose addresses are not tied to Linux users. List the domain in virtual_mailbox_domains and the addresses in virtual_mailbox_maps, and hand delivery to Dovecot over LMTP.

Choosing a domain class

Canonical domains are the name of the host itself; Postfix serves every other domain as a virtual one. A domain belongs to exactly one class.

ClassWhat you needWhen
Canonicalmydestination; recipients are Linux users and /etc/aliasesthe host’s own name, mail.example.com
Virtual aliasvirtual_alias_domains and virtual_alias_mapsthe domain only forwards mail to other addresses
Virtual mailboxvirtual_mailbox_domains, virtual_mailbox_maps, virtual_transportthe addresses have real mailboxes outside the system users

Configuring Postfix

inimain.cf
virtual_mailbox_domains = example.comvirtual_mailbox_maps = lmdb:/etc/postfix/vmailboxvirtual_transport = lmtp:unix:private/dovecot-lmtpvirtual_alias_maps = lmdb:/etc/postfix/virtual

virtual_mailbox_maps lists every existing address. When Dovecot rather than Postfix does the delivery over LMTP, Postfix ignores the value on the right: the table exists to reject unknown recipients. virtual_alias_maps defines aliases, including shared addresses such as postmaster.

text/etc/postfix/vmailbox
alice@example.com   OKbob@example.com     OK
text/etc/postfix/virtual
postmaster@example.com   alice@example.comabuse@example.com        alice@example.com
bashon the host
sudo postmap lmdb:/etc/postfix/vmailboxsudo postmap lmdb:/etc/postfix/virtualsudo postfix reload

Like the other Postfix tables, these files must be rebuilt with postmap after every change. The private/dovecot-lmtp socket is created by Dovecot; see “Dovecot: IMAP, LMTP, SASL and Maildir”.

The vmail user and mailbox directories

All virtual mailboxes belong to a single system user, vmail. The Postfix documentation uses uid and gid 5000 in its examples. The mailbox of alice@example.com lives in /var/vmail/example.com/alice/.

bashon the host
sudo groupadd -g 5000 vmailsudo useradd -u 5000 -g vmail -d /var/vmail \  -s /usr/sbin/nologin vmailsudo mkdir -p /var/vmailsudo chown vmail:vmail /var/vmailsudo chmod 700 /var/vmail

Dovecot: users in a passwd-file

In the Dovecot 2.4 format, users and passwords are stored in a passwd-file, whose lines follow the layout of /etc/passwd: user:password:uid:gid::home. Create the password hash with doveadm pw; it begins with the scheme name in curly braces. Paste the whole output of the command into the file in place of ....

bashon the host
doveadm pw -s ARGON2ID
text/etc/dovecot/users
alice@example.com:{ARGON2ID}...:5000:5000::/var/vmail/example.com/alicebob@example.com:{ARGON2ID}...:5000:5000::/var/vmail/example.com/bob
textdovecot.conf
passdb passwd-file {  passwd_file_path = /etc/dovecot/users} userdb passwd-file {  passwd_file_path = /etc/dovecot/users} mail_driver = maildirmail_path = ~/Maildir

The home field from userdb overrides the global mail_home; for virtual users it is optional but recommended. The ~ in mail_path stands for that directory, so the mailbox of alice ends up in /var/vmail/example.com/alice/Maildir. The file contains password hashes, so make it unreadable to other users.

One address list for Postfix and Dovecot

Postfix checks the recipient against vmailbox and virtual, and Dovecot checks it against its own users file. If an address is known to Postfix but not to Dovecot, the message is accepted but cannot be delivered: LMTP refuses it, and Postfix bounces the message to the sender. If an address exists only in Dovecot, Postfix replies User unknown. Keep the lists identical and do not turn off smtpd_reject_unlisted_recipient = yes: it is the default, and it rejects unknown recipients during the SMTP session.

How to check

bashon the host
postmap -q alice@example.com lmdb:/etc/postfix/vmailboxdoveadm user alice@example.comswaks --to alice@example.com --server 127.0.0.1 \  --quit-after RCPT

The first command confirms the address in the Postfix table, and the second confirms the user in Dovecot. swaks runs the SMTP dialogue up to the RCPT TO command without sending a message: a 250 reply means Postfix knows the address.

Section sources

the section is written from these pages

Dovecot: IMAP, LMTP, SASL and Maildir

Dovecot stores mail in Maildir, serves it to clients over IMAP, receives new messages from Postfix over LMTP, and checks the passwords of people who send mail through Postfix (SASL). It is linked to Postfix by two UNIX sockets.

How Postfix and Dovecot connect

Postfix hands Dovecot a message for a mailbox over LMTP (Local Mail Transfer Protocol, RFC 2033) and asks it whether a password is correct during SMTP AUTH. Both exchanges go through sockets in /var/spool/postfix/private: on Debian and Ubuntu, Postfix runs its processes in a chroot and they cannot see anything outside the queue directory. So Dovecot creates the sockets inside the Postfix directory, and the paths in main.cf are relative to it. An IMAP client has nothing to do with Postfix and connects to Dovecot directly.

The sockets live in the Postfix queue directory, so both processes can see them.

Dovecot 2.4 configuration

The 2.4 format is incompatible with 2.3: the file starts with a dovecot_config_version line, dovecot_storage_version is mandatory, and the plugin { ... } section is gone. Rewrite a 2.3 configuration by following the “2.3 to 2.4” page of the documentation. If your distribution package installs Dovecot 2.3, the examples below will not work. doveconf -n shows the resulting values.

inidovecot.conf
dovecot_config_version = 2.4.0dovecot_storage_version = 2.4.0 protocols {  imap = yes  lmtp = yes} mail_driver = maildirmail_home = /var/vmail/%{user}mail_path = ~/Maildirmail_uid = vmailmail_gid = vmail ssl = requiredssl_server_cert_file = /etc/dovecot/tls/fullchain.pemssl_server_key_file = /etc/dovecot/tls/privkey.pem auth_mechanisms = plain login passdb passwd-file {  passwd_file_path = /etc/dovecot/users}

Create the vmail user and group beforehand; if the vmail UID is below 500, set first_valid_uid. Storage for virtual mailboxes is covered in “Virtual domains and mailboxes”, and certificates in “TLS for SMTP and IMAP”. Several setting names changed in 2.4:

In 2.3In 2.4
mail_locationmail_driver, mail_path and other mail_* settings
ssl_cert, ssl_keyssl_server_cert_file, ssl_server_key_file
disable_plaintext_authauth_allow_cleartext
auth_debuglog_debug = category=auth

Maildir

In Maildir, each folder is a directory and each message is a separate file. A message is first written to tmp, then appears in new, and moves to cur once a client has seen it. The read flag and other markers are kept in the file name after :2,; S means “seen”. Messages can be added, changed and deleted without touching the other files, which makes the format efficient and safer on network file systems such as NFS.

The Dovecot documentation describes Maildir as suited mainly to small installations and supports it without prioritising new features. For a small server this is enough. If only Dovecot works with the Maildir directories directly, speed up synchronisation with maildir_very_dirty_syncs = yes.

Passwords: passdb and userdb

The password database (passdb) checks whether a password is correct. The user database (userdb) supplies mailbox data: UID, GID and home directory. In the example above these are set globally, so passdb alone is enough. The authentication mechanism (plain, login) and the password storage scheme are different things: the mechanism describes the exchange between client and server, and the scheme describes how the password is hashed in the database.

plain and login send the password in cleartext. While auth_allow_cleartext = no (the default), they work only over TLS. The login mechanism is needed mainly by Outlook clients for SMTP authentication, so both stay in the list. Check a password and look up a mailbox like this:

bashon the server
doveadm auth test anna@example.comdoveadm user anna@example.com

Without a second argument, doveadm auth test asks for the password itself, so it does not end up in your shell history.

LMTP for Postfix

LMTP is the recommended way to deliver mail to Dovecot. Enable the protocol in protocols and create the socket in the Postfix directory. If all mailboxes share one UID (virtual users), run the LMTP processes as that user.

inidovecot.conf
service lmtp {  # one UID for all mailboxes  user = vmail  unix_listener /var/spool/postfix/private/dovecot-lmtp {    mode = 0660    user = postfix    group = postfix  }}

SASL for Postfix

To check passwords, Dovecot opens the auth socket, and Postfix enables SASL of type dovecot. The main.cf parameters for both links:

inidovecot.conf
service auth {  unix_listener /var/spool/postfix/private/auth {    mode = 0660    user = postfix    group = postfix  }}
inimain.cf
virtual_transport = lmtp:unix:private/dovecot-lmtpsmtpd_sasl_type = dovecotsmtpd_sasl_path = private/authsmtpd_sasl_auth_enable = yes

For which Postfix services accept password login and how to restrict senders, see “Configuring Postfix: main.cf and master.cf”.

IMAP

Clients connect to port 143 (switching to TLS with the STARTTLS command) or to port 993 (TLS from the first packet). The ports are set by the imap-login service; with ssl = required, login without TLS is closed on both. mail_max_userip_connections (10 by default) limits the number of simultaneous connections from one user at one IP address.

inidovecot.conf
service imap-login {  inet_listener imap {    port = 143  }  inet_listener imaps {    port = 993    ssl = yes  }} mail_max_userip_connections = 20

Logs and debugging

By default Dovecot writes to syslog. To keep a separate file, set log_path; after rotation, reopen the file with doveadm log reopen. log_debug = category=auth turns on authentication debugging, with passwords masked. Enable it only while you track down a problem.

inidovecot.conf
log_path = /var/log/dovecot.log#log_debug = category=auth

What next

Server-side filters are provided by Sieve (the sieve plugin), quotas by the quota plugin, and full-text search by the fts and fts-flatcurve plugins. Setting them up is beyond the scope of this section; the Dovecot documentation covers it.

Section sources

the section is written from these pages

TLS for SMTP and IMAP

On the user-facing ports (465, 587, 993, 143), require TLS; on port 25, enable it where possible, otherwise some servers will not be able to deliver mail to you. Postfix and Dovecot can share one certificate for the name mail.example.com.

Ports and modes

Mail has two ways of enabling TLS. With STARTTLS (RFC 3207), the client connects unencrypted and a command upgrades the connection to TLS. With implicit TLS, the handshake begins right after the connection is made. RFC 8314 advises clients to prefer the second, but port 587 with STARTTLS stays in use: servers must support both. RFC 8314 does not apply to mail transfer between servers (port 25).

PortModeRequire TLS
25SMTP between servers, STARTTLSno: may
587submission, STARTTLSyes: encrypt
465submissions, implicit TLSyes: smtpd_tls_wrappermode=yes
143IMAP, STARTTLSyes: ssl = required
993IMAP, implicit TLSyes: ssl = required

Do not set encrypt on port 25 of a public server: RFC 3207 forbids it, and mail from senders without TLS would be rejected.

The certificate

Issue a single certificate for the name mail.example.com, the same one used in the MX and PTR records. Issuing through Let’s Encrypt is covered in the “TLS and PKI” reference, in the section on ACME. It produces the files fullchain.pem (the certificate with its chain) and privkey.pem (the key). Dovecot opens the key file as root, so the dovecot user needs no access to it.

Postfix reads the key and certificate through smtpd_tls_chain_files: the key comes first, followed by the certificate chain. The Postfix documentation advises against keeping them in separate files: when the key changes, a process may read a mismatched pair. Build a single file in a post-renewal hook and reload the services’ configuration.

bashpost-renewal hook
umask 077cat /etc/letsencrypt/live/mail.example.com/privkey.pem \    /etc/letsencrypt/live/mail.example.com/fullchain.pem \    > /etc/postfix/chain.pempostfix reloaddoveadm reload

After the first renewal, check with openssl s_client (see the last section) that the servers present the new certificate.

Postfix: receiving mail

By default smtpd_tls_security_level is empty, and Postfix does not offer TLS. The value may enables STARTTLS without making it mandatory. smtpd_tls_auth_only = yes stops Postfix from offering or accepting password login until TLS is active.

inimain.cf
smtpd_tls_chain_files = /etc/postfix/chain.pemsmtpd_tls_security_level = maysmtpd_tls_auth_only = yessmtpd_tls_loglevel = 1

For users, TLS is required only in master.cf: encrypt on 587 and wrapper mode on 465. The other parameters of these services are in “Configuring Postfix: main.cf and master.cf”.

inimaster.cf
submission inet n - n - - smtpd  -o smtpd_tls_security_level=encrypt  -o smtpd_sasl_auth_enable=yessubmissions inet n - n - - smtpd  -o smtpd_tls_wrappermode=yes  -o smtpd_sasl_auth_enable=yes

Protocol versions are restricted by smtpd_tls_protocols (for optional TLS) and smtpd_tls_mandatory_protocols (for mandatory TLS); since Postfix 3.6 their default is >=TLSv1. For users, RFC 8314 requires support for TLS 1.2 or newer and advises using it: set smtpd_tls_mandatory_protocols = >=TLSv1.2. Do not tighten versions on port 25, or you will lose some senders. The protocol and its versions are covered in the “TLS and PKI” reference.

Postfix: sending mail

With compatibility_level 3.11 or higher, smtp_tls_security_level defaults to may: Postfix encrypts if the recipient’s server supports TLS, and otherwise sends in cleartext. In earlier configurations the value is empty, meaning TLS is off. You can require TLS for particular recipients with the smtp_tls_policy_maps table.

inimain.cf
smtp_tls_security_level = maysmtp_tls_loglevel = 1smtp_tls_policy_maps = hash:/etc/postfix/tls_policy
text/etc/postfix/tls_policy
example.org    encrypt
bashon the server
sudo postmap /etc/postfix/tls_policy

Dovecot

ssl = yes offers TLS, and ssl = required demands it for the whole connection. Set ssl globally even if certificates are set per protocol, or Dovecot will not open the TLS ports. The minimum protocol version, ssl_min_protocol, defaults to TLSv1.2. Diffie–Hellman parameters (ssl_server_dh_file) are needed only for non-ECDSA certificates.

inidovecot.conf
ssl = requiredssl_server_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pemssl_server_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem

Ports 143 and 993, the imap-login service and password checking are covered in “Dovecot: IMAP, LMTP, SASL and Maildir”.

MTA-STS and TLS-RPT when sending

Postfix does not fetch the MTA-STS policies of other domains by itself. For that, attach a separate service through smtp_tls_policy_maps: postfix-tlspol or postfix-mta-sts-resolver. The smtp_tls_enforce_sts_mx_patterns parameter (yes by default, since Postfix 3.10.5) makes Postfix connect only to MX hosts from the policy if the service passes Postfix the data for TLSRPT. For publishing a policy and TLS-RPT records for your own domain, see “DNS for mail: MX, PTR, SPF, DMARC, MTA-STS”.

In Postfix 3.10 and newer, TLS-RPT (RFC 8460) collects the outcomes of TLS handshakes on outgoing connections: success or failure. Once a day these are compiled into reports for the domains that have published a policy. Postfix must be built with the TLSRPT library, and a separate tlsrpt-reporter service prepares the reports. Connections that break off before or after the handshake do not appear in the report.

inimain.cf
smtp_tlsrpt_enable = yessmtp_tlsrpt_socket_name = run/tlsrpt/tlsrpt.sock

REQUIRETLS (RFC 8689) is enabled by default in Postfix 3.11 (requiretls_enable): a message carrying this flag is sent only over TLS to a verified MX, and otherwise comes back as undeliverable.

Checking from outside

bashfrom another host
openssl s_client -starttls smtp -connect mail.example.com:25openssl s_client -starttls smtp -connect mail.example.com:587openssl s_client -connect mail.example.com:465openssl s_client -connect mail.example.com:993

In the output, look for Verify return code: 0 (ok). For troubleshooting certificate chain errors, see the “TLS and PKI” reference, in the section on diagnostics.

Section sources

the section is written from these pages

DKIM signing in Rspamd

DKIM signs outgoing mail with the domain’s private key, and the recipient verifies the signature with the public key published in DNS. In Rspamd, the dkim_signing module adds the signature: you generate a key with rspamadm dkim_keygen, publish a TXT record and give the module the path to the key.

How signing works

The signature (RFC 6376) covers selected headers and the message body and is added as a DKIM-Signature header. In it, d= is the signing domain, s= is the selector, h= is the list of signed headers, bh= is the body hash and b= is the signature itself. The recipient takes d= and s= and queries the TXT record <s>._domainkey.<d>. The selector lets a domain keep several keys, for example the old and new ones during a rotation.

Rspamd always uses relaxed/relaxed canonicalisation and the rsa-sha256 algorithm for RSA keys. It signs mail received from authenticated users, from local addresses and from the networks listed in sign_networks. For Rspamd to sign, it must scan outgoing mail: connecting it to Postfix is covered in “Spam filtering in Rspamd: checks and training”.

Creating a key

Use a 2048-bit RSA key: the Rspamd documentation calls 1024 bits a weak size, although RFC 6376 allows 1024 and up. Not all recipients support Ed25519, so use it only alongside RSA. The Rspamd process reads the key, so the directory and the file belong to the _rspamd user and everyone else is denied access.

bashon the server
sudo install -d -o _rspamd -g _rspamd -m 0750 /var/lib/rspamd/dkimsudo -u _rspamd rspamadm dkim_keygen -s mail2026 -d example.com \  -b 2048 -k /var/lib/rspamd/dkim/example.com.mail2026.keysudo chmod 0600 /var/lib/rspamd/dkim/example.com.mail2026.key

The private key goes to the file given by -k, and the command prints the DNS record to the screen. By default the file name is built as $domain.$selector.key, which is why the key is named this way.

textexample output
mail2026._domainkey IN TXT ( "v=DKIM1; k=rsa; "  "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..." ) ;

DNS record

Create a TXT record named mail2026._domainkey.example.com (in some control panels, just mail2026._domainkey) with the value v=DKIM1; k=rsa; p=.... A TXT string is at most 255 characters and a 2048-bit key is longer, so the value is split into several quoted strings; the recipient joins them with no spaces. Many control panels split the value for you. Check the record:

bashon any host
dig TXT mail2026._domainkey.example.com +short

Configuring the module

The file local.d/dkim_signing.conf sets the key path and the selector. The other parameters, including sign_authenticated = true and try_fallback = true, already have the right defaults, so you do not need to set them again.

inidkim_signing.conf
# /etc/rspamd/local.d/dkim_signing.confpath = "/var/lib/rspamd/dkim/$domain.$selector.key";selector = "mail2026";

The signing domain is taken from the From: header and reduced to the second-level domain. If an authenticated user sent the message, their login must end with @domain from From:, otherwise Rspamd will not sign the message. The allow_username_mismatch parameter relaxes this rule; enable it only deliberately.

bashon the server
sudo rspamadm configtestsudo systemctl restart rspamd

Several domains and selectors

If each domain needs its own selector, use selector_map: each line holds a domain and a selector separated by a space. The key path is then built from the path template, and path_map sets paths explicitly. If both maps are set and try_fallback = false, only the domains listed in them are signed.

text/etc/rspamd/dkim_selectors.map
example.com  mail2026example.org  mail2026
inidkim_signing.conf
selector_map = "/etc/rspamd/dkim_selectors.map";path = "/var/lib/rspamd/dkim/$domain.$selector.key";

Rotating a key without a gap

A recipient may verify a signature hours later, so do not delete the old record straight away (RFC 6376). The order of replacement:

  1. Create a key with a new selector, for example mail2027.
  2. Publish its TXT record and wait until dig shows it.
  3. Switch selector (or the entry in selector_map) to the new one and restart Rspamd.
  4. Wait until recipients have verified messages carrying the old signature: they may do so with a delay.
  5. Delete the old record and the key file.

Replace old 1024-bit keys the same way: the new key gets 2048 bits and a new selector.

Verifying

Send a message to an external mailbox of yours through submission with authentication and view the message source. It should have a DKIM-Signature header with d=example.com and s=mail2026, and dkim=pass in Authentication-Results. When signing, Rspamd sets the DKIM_SIGNED symbol.

bashon any host
swaks --server mail.example.com --port 587 --tls \  --auth LOGIN --auth-user anna@example.com \  --auth-password "$SMTP_PASSWORD" \  --from anna@example.com --to you@example.net

With check_pubkey = true, Rspamd compares the published public key with the private key when signing; this may add a DNS query at signing time.

Section sources

the section is written from these pages

Spam filtering in Rspamd: checks and training

Rspamd checks every incoming message with about a dozen modules, adds up the weights of the symbols that fired into a score and, based on thresholds, returns an action to Postfix: accept, defer, mark or reject. It talks to Postfix over the milter protocol.

If the action is “accept”, Postfix hands the message to Dovecot over LMTP.

Rspamd does not receive or send mail itself: it only gives a verdict, and Postfix carries it out. DKIM signing of outgoing mail is covered in “DKIM signing in Rspamd”, and SPF and DMARC DNS records in “DNS for mail”.

Connecting to Postfix

The rspamd_proxy worker listens on localhost:11332 in milter mode by default, so Rspamd needs no extra setup. Put your own Rspamd changes only in /etc/rspamd/local.d/ (they extend the defaults) or /etc/rspamd/override.d/ (they replace them): files in /etc/rspamd/ are updated together with the package.

ini/etc/postfix/main.cf
smtpd_milters = inet:127.0.0.1:11332non_smtpd_milters = $smtpd_miltersmilter_default_action = accept

non_smtpd_milters sends messages submitted locally with sendmail through Rspamd too. milter_default_action = accept decides what happens when Rspamd is unavailable: messages are accepted without scanning. In Postfix before 3.11 the default is tempfail, a temporary rejection after which senders retry later; from 3.11 it is shutdown, and Postfix closes the SMTP connection with a 421 reply.

bashon the server
sudo rspamadm configtestsudo systemctl restart rspamdsudo postfix reload

How the score is built

Each check adds a symbol with a weight, such as R_SPF_ALLOW or DMARC_POLICY_ALLOW, and the sum of the weights is compared with the thresholds in local.d/actions.conf. The thresholds from the documentation example:

inilocal.d/actions.conf
reject = 15;add_header = 6;greylist = 4;
ActionWhat Postfix gets
no actionthe message is accepted without any marking
greylist, soft rejecta temporary 4xx rejection; a retry will succeed
add headerthe message is accepted and a marker is added to the headers (in milter mode, X-Spam: Yes)
rewrite subjectthe message is accepted and its subject is replaced with the one set in subject
rejecta permanent rejection

soft reject has no threshold: modules issue it regardless of the score, for example greylisting and ratelimit. Write the settings in actions.conf without the actions { } wrapper, otherwise rspamadm configtest reports an error. The symbols behind a score are visible in the X-Spamd-Result header and in the web interface, and overall counters in rspamc stat.

SPF, DKIM and DMARC on receipt

The spf, dkim and dmarc modules work out of the box. They set symbols such as R_SPF_ALLOW, R_SPF_FAIL, R_DKIM_ALLOW, R_DKIM_REJECT, DMARC_POLICY_ALLOW, DMARC_POLICY_REJECT and DMARC_POLICY_QUARANTINE. By default, the sender’s p=reject policy only adds the DMARC_POLICY_REJECT symbol with a weight, so the score may fall short of the threshold. For the policy to produce an action directly, set one for each disposition.

inilocal.d/dmarc.conf
actions {  reject = "reject";  quarantine = "add header";  softfail = "no action";}

If you enable the reporting section, the module accumulates data for DMARC aggregate reports in Redis, and the rspamadm dmarc_report command, run from cron or a systemd timer, sends them. For more on reports, see “Deliverability and reputation”.

What the recipient sees

The milter_headers module adds the Authentication-Results header and spam markers. It adds the extended headers, including X-Spamd-Result, only to messages that do not come from authenticated users or from your own networks.

inilocal.d/milter_headers.conf
extended_spam_headers = true;use = ["authentication-results"];

Greylisting

Greylisting temporarily rejects a message with a 4xx code: a legitimate server will retry, while a spammer most often will not. The module defers only messages whose score has reached the greylist threshold, and only from a sender it sees for the first time. Message hashes are kept in Redis: by default timeout is 5 minutes and expire is 1 day. The price is a delay for the first message. The module is enabled as soon as a Redis server is specified.

inilocal.d/greylist.conf
servers = "127.0.0.1:6379";

DNSBLs

The rbl module checks the sender’s address, the links and the name in HELO against DNSBLs (DNS-based blocklists). Rspamd already has rules for the popular free lists. Every check is a DNS query, so the Rspamd quickstart advises installing your own local resolver. At the Postfix level, postscreen with the postscreen_dnsbl_sites parameter does similar work before the message is accepted.

Training

The Bayesian classifier (Bayes) keeps its statistics in Redis. Until min_learns messages have been loaded into it (200 in the documentation example), it gives no score. Train it on ready-made .eml files:

bashon the server
rspamc learn_spam spam.emlrspamc learn_ham ham.emlrspamc stat

Feeding the classifier by hand regularly is inconvenient. Have Dovecot IMAPSieve pass the messages that a user moves to the Spam folder and back to rspamc learn_spam and rspamc learn_ham: the setup is described in the Rspamd guide to user feedback through IMAPSieve. A Sieve script with fileinto on its own only files messages and does not train Rspamd.

Outgoing mail and the web interface

Your own users’ messages go through Rspamd as well. The ratelimit module keeps its counters in Redis and limits the number of messages per authenticated user, so a compromised account cannot send out thousands of spam messages.

inilocal.d/ratelimit.conf
rates {  user = {    bucket = {      burst = 100;      rate = "100 / 1min";    }  }}

Exceeding the limit produces a soft reject: Postfix temporarily rejects the message. The controller’s web interface runs on port 11334. Set a password generated with rspamadm pw in local.d/worker-controller.inc (password = "$2$…";), restrict the address with bind_socket = "127.0.0.1:11334"; and do not expose the port externally: the interface can change rules.

Section sources

the section is written from these pages

Deliverability and reputation

Messages from a new server land in spam because its address and domain have no reputation and the recipient cannot verify the sender. Since February 2024, Gmail and Yahoo have required authentication, correct DNS records and a low complaint rate; Gmail also requires TLS.

What decides whether a message reaches the inbox

The recipient weighs several signals at once, and a strong one does not make up for a weak one. Setting up the records themselves is covered in “DNS for mail: MX, PTR, SPF, DMARC, MTA-STS” and “DKIM signing in Rspamd”; here is what the large providers do with them.

SignalWhat the recipient checks
Domain authenticationSPF, DKIM and DMARC pass, and the domain in From matches the SPF or DKIM domain
Server name and addressthe IP has a PTR pointing to a name with an A or AAAA record for the same IP; the name is meaningful and does not look like a provider’s pool address
Encryptionthe message was delivered over TLS
IP and domain reputationthe sending history of this address and this domain, and whether either is on DNSBLs
Complaintsthe share of messages that readers marked as spam
Contenta well-formed message, visible links, no hidden text

Google requirements

The requirements for personal Gmail mailboxes have applied since 1 February 2024; the TLS requirement was added in December 2023. Messages without authentication may land in spam or be rejected with error 5.7.26.

RequirementApplies to
SPF or DKIM for the domainall senders
SPF and DKIM for the domain5,000 or more messages a day
DMARC, where the policy may be none5,000 or more messages a day
The domain in From aligned with the SPF or DKIM domain5,000 or more messages a day
Forward and reverse (PTR) records for the IPall senders
TLS in transitall senders
Complaint rate in Postmaster Tools below 0.3%all senders
RFC 5322 formatall senders
One-click unsubscribe and a visible link in the messagebulk mailings of 5,000 or more messages a day

For DKIM keys, Google requires a length of at least 1024 bits and recommends 2048 bits. It is better to keep the complaint rate below 0.10%: Google asks senders never to reach even 0.30%.

Yahoo requirements

Yahoo introduced its requirements in February 2024 and phased them in gradually. From bulk senders it additionally requires unsubscribing within 2 days.

RequirementApplies to
SPF or DKIMall senders
SPF and DKIMbulk senders
DMARC with a policy at least as strict as p=none, and the check passingbulk senders
The domain in From aligned with the SPF or DKIM domainbulk senders
Complaint rate below 0.3%all senders
Forward and reverse records for the IP, RFC 5321 and 5322all senders
One-click List-Unsubscribe and a link in the messagebulk senders

For mailings, Yahoo recommends the POST method per RFC 8058 and accepts mailto. It calculates the complaint rate from messages delivered to the inbox, and the Complaint Feedback Loop programme helps you track it.

Mailing headers

For mailings, add two headers: List-Unsubscribe with a link, and List-Unsubscribe-Post. Every message also needs a valid Message-ID and Date; the single-instance headers From, To, Subject and Date must not be repeated.

textmessage headers
List-Unsubscribe: <https://example.com/unsubscribe/abc123>List-Unsubscribe-Post: List-Unsubscribe=One-Click

New IP: warm-up

A new address has no history, so you increase volume gradually (warm-up). Start with a small number of messages to people who are expecting them, and raise the volume bit by bit. Send evenly, without spikes. If messages start bouncing or being deferred, lower the volume and then raise it again. Do not buy address lists: people who did not ask for your messages complain, and complaints lower your reputation.

DMARC reports

Recipients send aggregate reports (RFC 9990) to the address in the rua tag of your DMARC record. A report is an XML file, usually compressed with gzip (.xml.gz): one file holds the data of one recipient for one period.

ElementWhat it contains
policy_publishedthe policy of your DMARC record as the recipient saw it
source_ip, countthe sender’s address and the number of messages from it
policy_evaluatedthe disposition applied and the dkim and spf alignment
header_fromthe domain from the From header
auth_resultsthe SPF and DKIM results with their own domains

Read the reports like this: find all the source_ip values that send mail for your domain and make sure the genuine sources (your server, a mailing service) pass alignment: dkim or spf equals pass. Once all legitimate sources pass, move the policy from p=none to quarantine and then to reject. Failure reports (RFC 9991), requested with the ruf tag, send copies of individual messages in ARF format and may contain personal data, so many recipients do not send them.

Blocklists

If an IP lands on a DNSBL, first find the cause: an open relay, a compromised account, or mailing without consent. Only after fixing it, submit a delisting request to the list operator: if the cause is not removed, the address will be listed again. Google Postmaster Tools and Yahoo Sender Hub show the reputation of your address and domain with the large providers; a shared hosting address shares its reputation with its neighbours.

Testing by sending to yourself

Send a message to a mailbox at an outside provider, open the message source and find the Authentication-Results header: it shows what the recipient decided about SPF, DKIM and DMARC. You need pass for all three.

textexample output
Authentication-Results: mx.example.net; spf=pass smtp.mailfrom=example.com; dkim=pass header.d=example.com; dmarc=pass header.from=example.com

Section sources

the section is written from these pages

Mail server security

The server will not become an open relay as long as it relays mail only for its own authenticated users and local programs. Limits restrain brute force and overload, and password login is allowed only inside TLS.

Main threats

  • an open relay: anyone can send spam through your server, and its address ends up on DNSBLs
  • password guessing against submission and IMAP
  • spam sent from a compromised account
  • vulnerabilities in Postfix, Dovecot and Rspamd

Open relay

Postfix decides whether to relay a message at the RCPT TO command, using the smtpd_relay_restrictions list. It is read left to right and the end of the list means permit, so defer_unauth_destination comes last: it rejects recipients in other people’s domains. This is the default (since Postfix 2.10), but it is worth pinning explicitly together with mynetworks: only the server itself should be trusted.

inimain.cf
mynetworks = 127.0.0.0/8 [::1]/128smtpd_relay_restrictions =    permit_mynetworks,    permit_sasl_authenticated,    defer_unauth_destination

Two mistakes turn a server into an open relay. The network 0.0.0.0/0 in mynetworks makes the whole internet trusted, and a list without defer_unauth_destination at the end ends in permit.

inido not do this
mynetworks = 0.0.0.0/0smtpd_relay_restrictions =    permit_mynetworks,    permit_sasl_authenticated

Test the server from an outside address: a message to a recipient in a foreign domain should be rejected at RCPT TO.

bashfrom an outside host
swaks --server mail.example.com \  --from user@example.net \  --to someone@example.org \  --quit-after RCPT

Sender and recipient restrictions

smtpd_helo_required = yes requires HELO or EHLO before MAIL. smtpd_reject_unlisted_recipient is yes by default: messages to nonexistent recipients are rejected immediately, so the queue does not fill up with bounces. The reject_non_fqdn_* checks look only at the shape of the address, while reject_unknown_* query DNS, so place them later.

inimain.cf
smtpd_helo_required = yessmtpd_recipient_restrictions =    reject_non_fqdn_recipient,    reject_unknown_recipient_domain

To stop an authenticated user from sending as someone else’s address, create an smtpd_sender_login_maps table and enable reject_sender_login_mismatch. This restriction compares the login with the MAIL FROM address, not with the From header: only an external filter checks that. Enable the check for the submission service.

textmaster.cf
submission inet n - y - - smtpd  -o smtpd_sender_login_maps=hash:/etc/postfix/sender_logins  -o smtpd_sender_restrictions=reject_sender_login_mismatch  -o smtpd_client_message_rate_limit=60  -o smtpd_client_recipient_rate_limit=200
textsender_logins: address and login
info@example.com info@example.comadmin@example.com admin@example.com
bashon the server
sudo postmap /etc/postfix/sender_logins

Limits

Limits raise the cost of guessing and mass mailing. Postfix counters are calculated over the anvil_rate_time_unit interval (60 seconds by default). Adjust the values in the example above to your own load. Limits are meant against abuse, not for regulating normal traffic: be careful on port 25, which receives mail from legitimate servers.

ParameterWhat it limitsDefault
smtpd_client_connection_rate_limitconnections from a client per interval0, no limit
smtpd_client_message_rate_limitmessages from a client per interval0, no limit
smtpd_client_recipient_rate_limitrecipients from a client per interval0, no limit
smtpd_hard_error_limiterrors before the connection is dropped20, 1 under overload
smtpd_error_sleep_timedelay of replies after a series of errors1s
message_size_limitmessage size in bytes10240000
mail_max_userip_connections (Dovecot)IMAP connections from one user at one IP10
auth_failure_delay (Dovecot)delay of the reply to a wrong password2 secs

Postscreen and policy services

Under heavy load, postscreen shields port 25: it filters out bots before an smtpd process is started. Do not put it on submission, where your own users send mail. An external policy service is attached through check_policy_service and always comes after reject_unauth_destination, otherwise the server may become an open relay.

Login and accounts

smtpd_tls_auth_only = yes forbids advertising and accepting SASL login without encryption. The default is no, so set it yourself. In Dovecot 2.4, auth_allow_cleartext = no rejects a plaintext password without TLS; that is already the default. For more on TLS, see “TLS for SMTP and IMAP”.

inimain.cf
smtpd_tls_auth_only = yesdisable_vrfy_command = yes

disable_vrfy_command = yes turns off VRFY, which is used to harvest addresses. Require long passwords, and after a compromise change the password at once and check the queue: spam may have been sent from that account. Limit the number of messages in advance with a ratelimit rule in Rspamd (see “Spam filtering in Rspamd: checks and training”). Leave log-based blocking (fail2ban) and the firewall to the host; see the Linux security reference.

Updates

Postfix, Dovecot and Rspamd fix vulnerabilities in new versions. Follow the projects’ announcements; for the current branches and support periods, see “Versions and what’s new”.

ProjectWhere to follow
Postfixthe announcements page on postfix.org
Dovecotthe security page on dovecot.org
Rspamdthe changelog in the Rspamd documentation

Section sources

the section is written from these pages

Common errors and troubleshooting

To trace a missing message, follow its path: the Postfix log, the queue, DNS, the connection, the receiving server’s reply, the filter, delivery to the mailbox. The cause is almost always named in the log, on the line with status=deferred or status=bounced.

The red box marks an example: the message was accepted and vanished while being handed to Dovecot over LMTP.
  1. Log: /var/log/mail.log or sudo journalctl -u postfix. Find the queue ID and filter all of the message’s lines by it.
  2. Queue: postqueue -p shows the messages and why they are delayed; postcat -q ID shows the headers and envelope.
  3. DNS: dig MX example.com and dig -x 203.0.113.25 for your server’s address.
  4. Port and TLS: ss -ltnp and openssl s_client -starttls smtp -connect mail.example.com:25.
  5. Test send: swaks, which shows the whole SMTP dialogue.
bashon the host
sudo grep 3F2A1B4C5D /var/log/mail.logswaks --to user@example.com --server mail.example.com \  --quit-after RCPT

How to read a log line

The queue ID ties together all the entries for one message. In a delivery line, the important fields are to= (the recipient), relay= (the server Postfix talked to), delay= (the total delay), delays=a/b/c/d (its parts: from receipt of the message to its last entry into the active queue, until the connection started, connection setup, transmission), dsn= (the enhanced status code) and status=: sent — handed on, deferred — will retry later, bounced — rejected, and a notification goes back to the sender.

SMTP reply codes

The first digit of the code (RFC 5321, section 4.2) gives the class: 2xx — success, 4xx — temporary failure, try again later, 5xx — permanent failure. The enhanced status code X.Y.Z (RFC 3463) refines the reason: 5.1.1 — no such mailbox, 5.7.1 — rejected by policy, 4.7.0 — temporary security problem. IANA maintains the code registry.

CodeMeaningWhat to do
250Action completedNothing; keep looking along the message’s path
421Service not available, closing connectionRetry later; check load and limits
450Mailbox temporarily unavailable, including by policyWait for the retry; do not resend
451Error in processing on the serverWait for the retry; read the recipient’s log
452Insufficient system storageFree up space on the receiving side
454Temporary authentication failure (RFC 4954)Check Dovecot’s auth socket
550No such mailbox, or rejected by policyCheck the address; look at 5.1.1 or 5.7.1
552Exceeded storage allocationShrink the message or free up the mailbox
553Mailbox name not allowedCheck the address syntax
554Transaction failedRead the reply text and the X.Y.Z code

Relay access denied

Cause: Postfix does not consider the recipient’s domain its own, and the client has not authenticated. Either declare the domain in virtual_mailbox_domains (virtual mailboxes) or virtual_alias_domains, or have the client log in with SASL on port 587. The “Virtual domains and mailboxes” section describes how virtual domains are set up.

bashcheck
postconf virtual_mailbox_domains mydestination

mail for … loops back to myself

Cause: the domain’s MX points to this server, but Postfix does not consider the domain its own. This happens when a virtual domain is not declared in virtual_mailbox_domains or virtual_alias_domains. Never list a virtual domain in mydestination: a domain must be in exactly one list.

The message was accepted and vanished

Cause: Postfix replied 250 and handed the message to Dovecot, which did not accept it. Typical cases: the user is not in Dovecot’s database, the LMTP socket is unreachable, or the vmail mail store directory has the wrong permissions.

bashcheck
sudo doveadm user user@example.comls -l /var/spool/postfix/private/sudo journalctl -u dovecot -n 50

Login on port 587 fails

Cause: the client picked a SASL mechanism the server does not offer; login is allowed only after TLS (smtpd_tls_auth_only = yes) and the client did not enable STARTTLS; or Postfix cannot open Dovecot’s auth socket. First check the password with Dovecot itself, then the whole path.

bashcheck
sudo doveadm auth test user@example.comswaks --to user@example.com --server mail.example.com \  --port 587 -tls --auth LOGIN --auth-user user@example.com

Messages go out but land in spam

Open the full header at the recipient’s end and find Authentication-Results: it shows the SPF, DKIM and DMARC results. Also check the PTR record for your address. The records and how to check them are covered in “DNS for mail”, and reputation in “Deliverability and reputation”.

The queue keeps growing

Causes: the recipient is temporarily refusing mail because of reputation or rate limits, DNS is not working, or your hosting provider has blocked outbound port 25. postqueue -p shows the reason for each message. postqueue -f forces a delivery attempt; use it sparingly when there is no known cause, because flushing the queue often hurts delivery of the rest of your mail.

Verbose logging: temporarily

Turn verbose logging on only while you hunt for the error, then turn it back off: the log grows many times over and can contain message data.

iniPostfix
# Postfix: main.cf, then postfix reloaddebug_peer_list = 203.0.113.25 # Postfix: master.cf, -v at the end of the service line, then postfix reloadsmtp      inet  n       -       n       -       -       smtpd -v
iniDovecot and Rspamd
# Dovecot 2.4: dovecot.conflog_debug = category=auth # Rspamd: /etc/rspamd/local.d/logging.inclevel = "debug";

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Postfix 3.11, Dovecot 2.4 and Rspamd 4.2. The latest releases are Postfix 3.11.7 of 7 September 2026, Dovecot 2.4.5 of 28 August 2026 and Rspamd 4.2.3 of 21 October 2026.

Product, branchStatusLatest release
Postfix 3.11stable3.11.7 — 7 September 2026
Postfix 3.10legacy3.10.14 — 7 September 2026
Postfix 3.9legacy3.9.15 — 7 September 2026
Postfix 3.8legacy3.8.21 — 7 September 2026
Dovecot 2.4current2.4.5 — 28 August 2026
Dovecot 2.3no releases since August 20242.3.21.1 — 14 August 2024
Rspamd 4.2current4.2.3 — 21 October 2026
Rspamd 4.1no releases after 4.2.04.1.5 — 14 August 2026

Postfix ships the stable branch together with fixes for several earlier (legacy) branches: on 7 September 2026, for example, 3.11.7, 3.10.14, 3.9.15 and four more releases of older branches came out together. After 2.3.21.1, Dovecot’s announcements cover only 2.4 releases. For production, Rspamd recommends stable packages built from tagged releases rather than builds from the master branch.

Versions in distributions

A distribution freezes the version for the whole life of a release and backports fixes into it, so a package number does not tell you whether a vulnerability is closed: check the package changelog. The configurations in this reference are written for Dovecot 2.4 and will not work with Dovecot 2.3 on Ubuntu 24.04.

SystemPostfixDovecotRspamd
Debian 133.10.132.4.13.12.1
Ubuntu 24.043.8.62.3.213.8.1
Ubuntu 26.043.10.62.4.23.8.1

The table was compiled on 7 November 2026 from packages.debian.org and packages.ubuntu.com; check those pages before installing. Install a current Rspamd from the project’s own repository: its download pages describe it as the source of stable packages.

What changed in Postfix 3.11

  • Berkeley DB: some distributions are dropping support for it, and with it the hash: and btree: tables. The NON_BERKELEYDB_README page describes how to move to lmdb: or cdb:.
  • Outbound TLS: smtp_tls_security_level defaults to may if Postfix is built with TLS and compatibility_level is 3.11 or higher.
  • REQUIRETLS (RFC 8689): an ESMTP extension that requires strictly authenticated servers along the whole path of a message. Enable it with care; see REQUIRETLS_README.
  • Post-quantum cryptography: with OpenSSL 3.5 and later, the default of tls_eecdh_auto_curves has changed.
  • JSON output: postconf -j, as well as postalias -jq and postmap -jq.
  • Milter: milter_default_action now defaults to shutdown instead of tempfail, so on an error Postfix drops the connection to the client.

What changed in Dovecot 2.4

  • The first setting in dovecot.conf must be dovecot_config_version.
  • Settings are no longer nested in a hierarchy: all of them are global, and a filter block sets where they apply. The passdb and userdb sections require a name, and the plugin section is gone: plugin settings are global too.
  • ssl_cert, ssl_key and ssl_dh are renamed ssl_server_cert_file, ssl_server_key_file and ssl_server_dh_file; ssl_ca is split into ssl_server_ca_file and ssl_client_ca_file.
  • disable_plaintext_auth is replaced by auth_allow_cleartext, and auth_debug by the log_debug filter.
  • mail_location is split into mail_driver and mail_path.
diffdovecot.conf: 2.3 and 2.4
-mail_location = maildir:~/+mail_path = ~/+mail_driver = maildir

Follow the official “2.3 to 2.4” page strictly when moving from 2.3 to 2.4: it also lists every renamed and removed setting.

What changed in Rspamd 4

  • 4.0: the /checkv3 protocol appeared; include_content_urls now defaults to true; the worker option ssl = true was removed, and the senderscore_reputation rule is off by default.
  • 4.1: the mx_check check was reworked, and the MX_NONE symbol replaced MX_NXDOMAIN and MX_MISSING.
  • 4.2: a single symbol scheduler instead of several; the multimap top filter returns the full public suffix, so maps need entries such as com.au rather than au.

Deprecated and removed

  • RFC 7489 is replaced by RFC 9989 (DMARC), RFC 9990 (aggregate reports) and RFC 9991 (failure reports), published in May 2026.
  • The pct tag in DMARC is removed; the t tag with the values y and n replaces it.
  • Set smtpd_tls_wrappermode = yes only in master.cf, on the service line for port 465, not in main.cf.

Security updates

IdentifierWhat is affectedFixed in
CVE-2026-27852Dovecot: a message with a huge number of addresses in its headers causes excessive memory use2.4.5
CVE-2026-33605Pigeonhole: the ManageSieve login process crashes before authentication2.4.5
CVE-2026-42391Dovecot: the IMAP ID command before login loads memory and CPU2.4.5
CVE-2026-73208Dovecot: OAuth2 accepted a token issued for a different purpose, based on the aud field2.4.5
CVE-2026-42007Pigeonhole: use-after-free in the editheader Sieve extension2.4.5
CVE-2026-27851Dovecot: the safe filter marked unsafe data as safe2.4.4
no CVERspamd: a $1$ password hash in the controller accepted any password4.1.4
no CVERspamd: heap overflow when parsing chunked HTTP messages4.2.1
no CVERspamd: heap overflow in lower_utf84.2.2
no CVERspamd: an allowlisted ARC signature with a failed verification was treated as trusted4.2.3

This is a selection: on 28 August 2026 Dovecot published 25 advisories, and the full list is on its security page. The Postfix release list has no entries about vulnerabilities.

How to upgrade

Upgrade the products one at a time and check the configuration after each step: that way an error is easy to tie to the release that introduced it.

bashon the host
sudo apt updatesudo apt install --only-upgrade rspamdsudo rspamadm configtestsudo apt install --only-upgrade postfixsudo postfix checksudo apt install --only-upgrade dovecot-core# configuration errors go to stderrsudo doveconf -n > /dev/null

sudo apt upgrade updates everything at once, and if something breaks it is harder to tell which package is to blame. Read each product’s changelog: Rspamd 4.2 changes the semantics of maps, and Postfix 3.11 changes the TLS defaults.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Mail server” topic
12 sections
Another reference · DevOps & cloud

Ansible

Verified 6 Nov
All references · 61