1. 準備工作
確保服務器具備公網IP地址(或通過SSH反向隧道配置間接遠程訪問),并擁有有效域名(如mail.example.com
,需指向服務器IP)。同時,完成域名DNS解析:添加A記錄
(mail.example.com
指向服務器IP)和MX記錄
(example.com
指向mail.example.com
,優先級設為10)。
2. 安裝Postfix(MTA,郵件傳輸代理)
Postfix是Debian下常用的郵件傳輸代理,負責郵件收發。執行以下命令安裝:
sudo apt update && sudo apt install postfix -y
安裝過程中,系統會提示選擇配置類型,推薦選擇Internet Site(適用于公開郵件服務器),并填寫郵件域名(如example.com
)。
3. 配置Postfix允許遠程訪問
編輯Postfix主配置文件/etc/postfix/main.cf
,修改以下關鍵參數:
sudo nano /etc/postfix/main.cf
myhostname = mail.example.com # 郵件服務器主機名
mydomain = example.com # 郵件域名
myorigin = $mydomain # 發送郵件時的發件域
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 127.0.0.0/8, 192.168.1.0/24 # 允許的中繼網絡(可根據需求調整)
smtpd_sasl_type = dovecot # 使用Dovecot提供SASL認證
smtpd_sasl_path = private/auth # Dovecot認證套接字路徑
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous # 禁止匿名認證
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
保存文件后,重啟Postfix使配置生效:
sudo systemctl restart postfix
4. 安裝Dovecot(IMAP/SMTP服務器)
Dovecot提供IMAP/SMTP協議支持,允許郵件客戶端(如Outlook、Thunderbird)遠程訪問郵箱。執行以下命令安裝:
sudo apt install dovecot-imapd dovecot-pop3d -y
安裝完成后,編輯Dovecot配置文件/etc/dovecot/conf.d/10-auth.conf
,啟用明文認證(需配合SSL/TLS使用,后續步驟會配置):
sudo nano /etc/dovecot/conf.d/10-auth.conf
修改以下參數:
disable_plaintext_auth = no # 允許明文認證(僅用于測試,生產環境建議啟用SSL后設為yes)
auth_mechanisms = plain login # 支持的認證機制
再編輯/etc/dovecot/conf.d/10-mail.conf
,設置郵件存儲路徑(與Postfix一致):
mail_location = mbox:/var/mail/%u # 郵件存儲在/var/mail/用戶名目錄下
保存文件后,重啟Dovecot:
sudo systemctl restart dovecot
5. 配置防火墻開放端口
使用ufw
(Uncomplicated Firewall)開放郵件服務所需端口:
執行以下命令:
sudo ufw allow 25/tcp # SMTP
sudo ufw allow 465/tcp # SMTPS
sudo ufw allow 143/tcp # IMAP
sudo ufw allow 993/tcp # IMAPS
sudo ufw allow 110/tcp # POP3
sudo ufw allow 995/tcp # POP3S
sudo ufw enable # 啟用防火墻
6. 配置SSL/TLS加密(提升安全性)
為避免郵件傳輸被竊聽,需為Postfix和Dovecot配置SSL/TLS證書。推薦使用Let’s Encrypt免費獲取證書:
sudo apt install certbot python3-certbot-postfix python3-certbot-dovecot -y
為Postfix申請證書:
sudo certbot --postfix -d mail.example.com
為Dovecot申請證書(Let’s Encrypt會自動復用Postfix的證書,無需重復申請):
sudo certbot --dovecot -d mail.example.com
證書申請完成后,Postfix和Dovecot會自動加載證書。無需手動修改配置文件(默認路徑為/etc/letsencrypt/live/mail.example.com/
)。
7. 創建郵件用戶并測試
創建系統用戶作為郵件賬戶(如mailuser
):
sudo adduser mailuser
設置強密碼(遵循密碼策略,包含大小寫字母、數字和特殊字符)。
使用郵件客戶端(如Thunderbird)配置賬戶:
mail.example.com
;mailuser
/設置的密碼;8. 安全增強措施
/etc/ssh/sshd_config
,設置PermitRootLogin no
,重啟SSH服務:sudo systemctl restart ssh
ssh-keygen -t rsa
),將公鑰復制到服務器(ssh-copy-id remoteuser@mail.example.com
),并在/etc/ssh/sshd_config
中設置PubkeyAuthentication yes
、PasswordAuthentication no
,重啟SSH服務。sudo apt update && sudo apt upgrade -y
,修補安全漏洞。/etc/postfix/main.cf
中的mynetworks
設置為僅允許信任的IP段(如公司內網),減少中繼風險。