️ Postfix — SMTP Mail Server
If you like this project, consider supporting me on Buy Me a Coffee ☕️
tags:
- smtp
- postfix
- sysadmin
-
linux
✉️ Postfix Cheatsheet
Description
Postfix is a widely used open-source MTA (Mail Transfer Agent) for routing and delivering SMTP mail. It handles submission, relay, local delivery, and can work with Dovecot for IMAP/POP and amavisd/ClamAV for filtering. / Postfix — распространённый MTA для SMTP: маршрутизация, ретрансляция, локальная доставка; часто в паре с Dovecot (IMAP/POP) и фильтрами.
Common use cases / Типовые сценарии:
- Outbound relay for servers/apps / Исходящий релей для серверов и приложений
- Inbound MX for a domain / Приём почты MX для домена
- Internal mail hub for monitoring/alerts / Внутренний хаб для алертов
- Relay to Google Workspace / Microsoft 365 / Релей в облачные почтовые сервисы
Status: Actively maintained (Wietse Venema / IBM Research). Alternatives: Exim, sendmail (legacy), msmtp (client-only), Haraka (Node.js). / Статус: активно развивается; альтернативы — Exim, sendmail, msmtp.
Default ports: 25/tcp (SMTP), 587/tcp (submission), 465/tcp (SMTPS, if enabled).
Paths: config /etc/postfix/main.cf, /etc/postfix/master.cf; queue /var/spool/postfix; logs journalctl -u postfix.
Cross-reference: Dovecot, OpenLDAP, firewalld, Nginx.
Installation
Install Postfix / Установка Postfix
# Debian/Ubuntu
export DEBIAN_FRONTEND=noninteractive
apt install postfix
# RHEL/Rocky/Alma/Fedora
dnf install postfix
# SUSE
zypper install postfix
postfix -v
postconf -d | grep -E 'myhostname|mydomain|inet_interfaces'
Common package set / Типовой набор пакетов
# Debian/Ubuntu (full mail stack example)
apt install postfix dovecot-imapd dovecot-pop3d postfix-pcre mailutils
# RHEL
dnf install postfix dovecot dovecot-pgsql mailx
Configuration
Main files / Основные файлы
/etc/postfix/main.cf
/etc/postfix/master.cf
/etc/postfix/postfix.conf (if present)
/var/spool/postfix/ (queue dirs: incoming, active, deferred, maildrop, etc.)
/etc/aliases (local alias map)
Core main.cf / Базовая конфигурация main.cf
/etc/postfix/main.cf
# Identity
myhostname = mail.<DOMAIN>
mydomain = <DOMAIN>
myorigin = $mydomain
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
inet_interfaces = all
inet_protocols = ipv4
# Relay restrictions
mynetworks = 127.0.0.0/8, [::1]/128, 10.0.0.0/8
relay_domains =
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination
# TLS (recommended)
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.<DOMAIN>/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.<DOMAIN>/privkey.pem
smtpd_tls_security_level = may
smtpd_tls_auth_only = yes
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_mandatory_ciphers = high
# SASL via Dovecot (optional but recommended for submission)
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous, noplaintext
smtpd_sasl_tls_security_options = noanonymous
# Outbound TLS
smtp_tls_security_level = dane
smtp_tls_note_starttls_offer = yes
# Queue / delivery
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/lib/postfix/sbin
data_directory = /var/lib/postfix
mail_owner = postfix
setgid_group = postfix
# Timeouts (seconds)
smtpd_timeout = 300s
smtpd_hard_error_limit = yes
default_process_limit = 100
queue_minfree = 0
# Optional: local destination for monitoring
# local_recipient_maps =
Submission port / Порт отправки (587)
/etc/postfix/master.cf
# uncomment / add submission
smtp inet n - y - - smtpd
submission inet n - y - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_tls_auth_only=yes
-o smtpd_reject_unlisted_recipient=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING
-o smtpd_sender_restrictions=reject_sender_login_mismatch
Aliases / Алиасы
/etc/aliases
postmaster: root
abuse: abuse@<DOMAIN>
root: <ADMIN_EMAIL>
newaliases # rebuild aliases.db
Validation / Проверка конфигурации
postconf -n # show non-default settings
postconf -e # edit main.cf
postcheck # syntax check (if available)
Core Management
Service control / Управление сервисом
systemctl status postfix
systemctl restart postfix
systemctl reload postfix
postfix start
postfix stop
postfix reload
postfix flush # flush queue
postfix check # consistency check
Queue management / Управление очередью
mailq # list queue
postqueue -f # flush all
postqueue -j | head # JSON queue info
postsuper -d ALL # delete ALL queued mail (destructive)
postsuper -d <QUEUE_ID> # delete one
postsuper -r ALL # requeue all
postsuper -s 1h # requeue deferred older than 1h
[!CAUTION]
postsuper -d ALLpermanently deletes all queued mail. Double-check queue IDs first. /postsuper -d ALLудаляет всю очередь — проверьте очередь заранее.
Manual send / Ручная отправка
echo -e "Subject: test\n\nhello" | mail -s "test" root@localhost
printf "Subject: test\n\nhello\n" | sendmail -t root@localhost
Sysadmin Operations
Logs / Логи
journalctl -u postfix --no-pager -n 50
tail -f /var/log/mail.log # Debian/Ubuntu
tail -f /var/log/maillog # RHEL family
postqueue -p | head
Queue monitoring / Мониторинг очереди
# Alert if deferred grows
postqueue -p | awk '/^--/{n++} END{print n+0} deferred items'
Logrotate / Ротация логов
/etc/logrotate.d/postfix
/var/log/mail.log {
weekly
rotate 4
compress
delaycompress
missingok
notifempty
sharedscripts
postrotate
systemctl kill -s HUP postfix >/dev/null 2>&1 || true
endscript
}
Security
Hardening checklist / Чек-лист ужесточения
- Enable TLS with strong ciphers on 25/587 / Включите TLS
- Restrict
mynetworksto known sources / Ограничьте mynetworks - Require SASL for submission (587) / Требуйте SASL на 587
- Reject unauthenticated relaying / Запрещайте неаутентифицированную ретрансляцию
- Set SPF/DKIM/DMARC for outbound / Настройте SPF/DKIM/DMARC
- Rate-limit connections (if supported) / Ограничивайте соединения
- Monitor deferred queue and open-relay risk / Мониторьте очередь и open-relay
- Keep Postfix updated / Обновляйте Postfix
# Verify TLS config
postconf -n | grep smtpd_tls
SPF/DKIM/DMARC (outbound) / Внешняя аутентификация
# SPF (DNS TXT): v=spf1 ip4:<SERVER_IP> -all
# DKIM: use opendkim/milter (external to core Postfix)
# DMARC (DNS TXT): v=DMARC1; p=reject; rua=mailto:dmarc@<DOMAIN>
Backup and Restore
Backup / Резервное копирование
tar czf /var/backups/postfix-config-$(date +%F).tar.gz \
/etc/postfix /etc/aliases
# Optionally copy deferred queue
tar czf /var/backups/postfix-queue-$(date +%F).tar.gz /var/spool/postfix/deferred
Restore / Восстановление
systemctl stop postfix
tar xzf /var/backups/postfix-config-<DATE>.tar.gz -C /
postfix check
systemctl start postfix
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
Relay access denied |
Not in mynetworks / no SASL | Check mynetworks; enable SASL |
No route to host on 25 |
Firewall / port blocked | Open outbound 25/tcp |
| Mail stuck in deferred | DNS / remote timeouts | postqueue -p; check maillog |
Temporary lookup failure |
Postfix master down | Restart postfix; check master.cf |
| TLS errors on outbound | Cert path / remote TLS | smtp_tls_security_level=dane; verify certs |
| SASL login failed | Dovecot auth socket | Check smtpd_sasl_path; Dovecot auth |
postconf -n | grep -E 'mynetworks|sasl|relay'
postqueue -p | head
journalctl -u postfix -f
Comparison Tables
MTAs / МТA (Mail Transfer Agents)
| Tool | Strengths | Typical use |
|---|---|---|
| Postfix | Secure, modular, easy config | Modern Linux MTA |
| Exim | Flexible routing | Debian default historically |
| sendmail | Legacy compatibility | Old systems |
| msmtp | Lightweight client | Outbound-only from servers |
| Haraka | Node.js extensibility | Custom pipelines |
Production Runbooks
Runbook: New domain MX / Настройка MX для нового домена
- Install postfix + TLS certs / Установить postfix и сертификаты
- Set
myhostname,mydomain,mydestination/ Настроить identity - Configure
inet_interfacesandmynetworks/ Настроить интерфейсы - Enable TLS + submission on 587 / Включить TLS и 587
- Restart postfix; verify listening ports / Перезапустить и проверить порты
- Publish MX record; verify with
dig MX <DOMAIN>/ Опубликовать MX - Test inbound:
swaks --to postmaster@<DOMAIN>/ Проверить приём - Test outbound: send from local / Проверить исходящую почту
Runbook: Deferred queue cleanup / Очистка отложенной очереди
postqueue -p— identify deferred IDs / Просмотреть очередь- Check DNS/remote reachability / Проверить DNS и сеть
postsuper -r <QUEUE_ID>— requeue selected / Перепоставить выбранные- Flush:
postfix flush/ Сбросить очередь - If spam/bounce storm: delete by ID only / Удаляйте только по ID
- Document root cause for next runbook / Задокументировать причину
Documentation Links
- Postfix docs — https://www.postfix.org/documentation.html
- postconf(5) — https://www.postfix.org/postconf.5.html
- master.cf — https://www.postfix.org/master.5.html
- Postfix security — https://www.postfix.org/SECURITY_README.html
- Postfix on Debian — https://wiki.debian.org/Postfix