本指南從零開始建立一台完整的生產級自建郵件伺服器,完成後你將擁有:Postfix(SMTP)、Dovecot(IMAP/POP3)、全程 TLS 加密、SPF/DKIM/DMARC 以及虛擬信箱支援。
前提條件
- 全新的 Ubuntu 22.04 VPS,至少 1 GB 記憶體
- 網域名稱:
example.com,郵件子網域:mail.example.com - 防火牆已開放 25、587、993、995 埠
第一階段:系統準備
sudo apt update && sudo apt upgrade -y
sudo hostnamectl set-hostname mail.example.com
sudo apt install -y postfix dovecot-core dovecot-imapd dovecot-pop3d \
opendkim opendkim-tools certbot mailutils
第二階段:申請 TLS 憑證
sudo certbot certonly --standalone -d mail.example.com
cat > /etc/letsencrypt/renewal-hooks/post/mail.sh << 'EOF'
#!/bin/bash
systemctl reload postfix dovecot
EOF
chmod +x /etc/letsencrypt/renewal-hooks/post/mail.sh
第三階段:設定 Postfix
main.cf
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
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_security_level = may
smtp_tls_security_level = may
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
virtual_mailbox_domains = example.com
virtual_mailbox_base = /var/mail/vhosts
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
milter_default_action = accept
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891
建立虛擬信箱目錄
sudo groupadd -g 5000 vmail
sudo useradd -g vmail -u 5000 vmail -d /var/mail/vhosts
sudo mkdir -p /var/mail/vhosts/example.com
sudo chown -R vmail:vmail /var/mail/vhosts
第四階段:設定 Dovecot
10-mail.conf:
mail_location = maildir:/var/mail/vhosts/%d/%n
mail_uid = vmail
mail_gid = vmail
10-ssl.conf:
ssl = required
ssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pem
ssl_min_protocol = TLSv1.2
第五階段:設定 DKIM
sudo mkdir -p /etc/opendkim/keys/example.com
sudo opendkim-genkey -b 2048 -d example.com -s mail -D /etc/opendkim/keys/example.com/
sudo chown -R opendkim:opendkim /etc/opendkim/keys/
cat /etc/opendkim/keys/example.com/mail.txt
第六階段:DNS 記錄
| 類型 | 名稱 | 值 |
|---|---|---|
| MX | example.com | mail.example.com(優先級 10) |
| A | mail.example.com | 伺服器 IP |
| TXT | example.com | v=spf1 ip4:伺服器IP ~all |
| TXT | mail._domainkey.example.com | (來自 mail.txt 的內容) |
| TXT | _dmarc.example.com | v=DMARC1; p=none; rua=mailto:admin@example.com |
第七階段:啟動並測試
sudo systemctl restart opendkim postfix dovecot
sudo systemctl enable opendkim postfix dovecot
echo "測試郵件內文" | mail -s "測試" someone@gmail.com
sudo tail -f /var/log/mail.log