建立完整郵件伺服器:Ubuntu 22.04 上的 Postfix + Dovecot

Postfix Dovecot 郵件伺服器 Ubuntu 生產環境
披露:Email Wiki 上的部分連結為 VPS 服務商(如 Vultr)的聯盟連結。透過這些連結購買,我們可能獲得佣金,但不會對您產生額外費用。這有助於我們維持網站免費。所有教程均獨立撰寫,我們僅推薦適合自建郵件伺服器的可靠服務。

本指南從零開始建立一台完整的生產級自建郵件伺服器,完成後你將擁有: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 記錄

類型名稱
MXexample.commail.example.com(優先級 10)
Amail.example.com伺服器 IP
TXTexample.comv=spf1 ip4:伺服器IP ~all
TXTmail._domainkey.example.com(來自 mail.txt 的內容)
TXT_dmarc.example.comv=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

準備好部署你的郵件伺服器了嗎?

你需要一台 IP 信譽乾淨的可靠 VPS。立即使用 Vultr——獨立 IP、NVMe SSD、全球資料中心,最低 $6/月。