大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
邮件系统搭建与日常运维
把 dnm-smtp、dnm-imap、dnm-auth-mail 串联起来:Postfix 发信 + Dovecot 收信 + DNS 认证 + 监控备份。本课给出单机最小可用栈与 relay 混合架构(推荐生产),结合 linux-essentials 服务管理、networking-essentials 防火墙与端口、dns-essentials 记录配置、git-essentials 配置版本化。
学习目标
- 部署 Postfix + Dovecot 最小邮件栈(或 relay 架构)
- 配置 Let's Encrypt 证书与防火墙规则
- 建立邮件系统 监控、队列、备份 日常 SOP
架构选型
| 架构 | 组件 | 适用 |
|---|---|---|
| Relay 混合(推荐) | Postfix relay → SendGrid/SES;Dovecot 仅内网 IMAP | SaaS 发信 + 自建收信 |
| 全自建 MTA | Postfix 直连 25 端口 | 需 IP 信誉、反垃圾运维 |
| 全 SaaS | 无 Postfix,API 发 + 云邮箱收 | 小团队、零运维 |
Relay 混合架构
App ──587──► Postfix ──relay──► SendGrid ──► 互联网
运维 ──993──► Dovecot ──► Maildir(内网/archive)
DNS: MX + SPF + DKIM + DMARC
安装与基础配置
# Debian/Ubuntu
sudo apt update
sudo apt install postfix dovecot-imapd dovecot-lmtpd certbot
# Postfix 安装时选 "Internet Site",mydomain = example.com
/etc/postfix/main.cf(relay 模式):
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
relayhost = [smtp.sendgrid.net]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_security_level = encrypt
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem
sudo postmap /etc/postfix/sasl_passwd
sudo systemctl enable --now postfix dovecot
DNS 一次性清单
A mail.example.com → 203.0.113.10
MX @ → mail.example.com (priority 10)
TXT @ → v=spf1 ip4:203.0.113.10 include:sendgrid.net ~all
TXT mail._domainkey → v=DKIM1; k=rsa; p=...
TXT _dmarc → v=DMARC1; p=quarantine; rua=mailto:dmarc@example.com
详见 dnm-auth-mail。
防火墙
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp # certbot HTTP-01
sudo ufw allow 443/tcp
sudo ufw allow 587/tcp # Submission(若对外)
sudo ufw allow 993/tcp # IMAPS
# 25 通常不对公网开放,relay 模式不需要
sudo ufw enable
参考 net-firewall。
证书续期
sudo certbot certonly --nginx -d mail.example.com
# 或 standalone / DNS-01(wildcard 用 DNS 插件)
# 续期 hook 重载服务
echo 'deploy_hook = systemctl reload postfix dovecot' | \
sudo tee -a /etc/letsencrypt/cli.ini
日常运维 SOP
队列监控
mailq # 查看 Postfix 队列
postqueue -p | head
sudo postsuper -d ALL deferred # 谨慎:清空 deferred 队列
日志
journalctl -u postfix -f
journalctl -u dovecot -f
grep "status=sent" /var/log/mail.log | tail
grep "authentication failure" /var/log/mail.log
备份
# Maildir + 配置
tar czf mail-backup-$(date +%F).tar.gz \
/var/mail/vhosts \
/etc/postfix \
/etc/dovecot
脚本纳入 dnm-programming 与 Git。
健康检查
# 端口
ss -tlnp | grep -E 'postfix|dovecot'
# 发信测试
swaks --to self@example.com --from noreply@example.com \
--server localhost:587 --auth LOGIN --tls
# IMAP 测试
doveadm auth test ops@example.com password
练习
- 画出你的邮件架构图(relay 或全自建),标注端口与 DNS 记录
- 编写
mailq+ 日志 grep 的巡检脚本,cron 每 15 分钟跑一次 - 列出证书续期失败时的 3 步应急流程
小结
邮件运维 = Postfix/Dovecot 服务 + DNS 认证 + 防火墙 + 队列/日志/备份 SOP。 生产推荐 relay 发信降低 IP 信誉成本。下一课综合练习。