确保已搭建好LNMP(Linux+Nginx+MySQL/MariaDB+PHP)环境。若未搭建,可参考标准流程安装:
sudo apt update && sudo apt upgrade -yphp-fpm、php-mysql)。邮件服务需Postfix(MTA,处理邮件收发)和Dovecot(IMAP/SMTP,处理邮件客户端连接),同时安装mailutils用于命令行测试:
sudo apt update
sudo apt install postfix dovecot-core dovecot-imapd dovecot-lmtpd mailutils -y
安装过程中,Postfix会提示选择配置类型,选**“Internet Site”**(适用于公开邮件服务器);Dovecot默认配置即可满足基础需求。
编辑Postfix主配置文件/etc/postfix/main.cf,修改以下关键参数:
sudo nano /etc/postfix/main.cf
myhostname = mail.yourdomain.com # 邮件服务器主机名(需替换为实际域名)
mydomain = yourdomain.com # 主域名
myorigin = $mydomain # 发件人域名默认值
inet_interfaces = all # 监听所有网络接口
inet_protocols = ipv4 # 仅使用IPv4(若需IPv6可改为“all”)
home_mailbox = Maildir/ # 用户邮件存储格式为Maildir(目录结构)
mydestination = $myhostname, localhost.$mydomain, $mydomain # 允许接收的域名
mynetworks = 127.0.0.0/8 [::1]/128 # 允许中继的IP(本地网络)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
smtpd_recipient_restrictions = permit_mynetworks permit_sasl_authenticated reject_unauth_destination
保存后重启Postfix:sudo systemctl restart postfix。
编辑Dovecot主配置文件/etc/dovecot/dovecot.conf,设置邮件存储路径和协议:
sudo nano /etc/dovecot/dovecot.conf
mail_location = maildir:~/Maildir # 必须与Postfix的home_mailbox一致
protocols = imap pop3 # 开启IMAP(加密推荐)和POP3协议
编辑SASL认证配置/etc/dovecot/conf.d/10-auth.conf,允许明文认证(客户端需支持):
sudo nano /etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = no # 允许明文认证(生产环境建议开启SSL后设为yes)
auth_mechanisms = plain login # 支持的认证机制
保存后重启Dovecot:sudo systemctl restart dovecot。
sudo systemctl start postfix
sudo systemctl enable postfix
sudo systemctl start dovecot
sudo systemctl enable dovecot
通过systemctl status postfix和systemctl status dovecot检查服务状态(显示“active (running)”即为正常)。
允许邮件服务所需端口(SMTP:25、IMAP:143、POP3:110)通过防火墙:
sudo ufw allow 25/tcp # SMTP(邮件发送)
sudo ufw allow 143/tcp # IMAP(邮件接收,明文)
sudo ufw allow 110/tcp # POP3(邮件接收,明文)
sudo ufw reload # 重新加载防火墙规则
命令行测试SMTP:
telnet localhost 25
输入以下命令模拟发送邮件(替换为实际邮箱):
HELO localhost
MAIL FROM: <your-email@yourdomain.com>
RCPT TO: <recipient@example.com>
DATA
Subject: Test Email from Debian Mail Server
This is a test email sent from your Debian mail server.
.
QUIT
若收到“250 2.0.0 Ok: queued as XXXXXXX”的响应,说明SMTP发送正常。
命令行测试IMAP:
openssl s_client -connect localhost:143 -crlf
输入以下命令登录邮箱(替换为实际用户名/密码):
a1 LOGIN your-username your-password
a2 LIST "" *
a3 SELECT INBOX
a4 FETCH 1 BODY[HEADER]
a5 LOGOUT
若能获取邮件头信息,说明IMAP连接正常。
邮件服务需通过DNS解析识别,需在域名管理面板添加以下记录:
mail.yourdomain.com),优先级设为10;mail.yourdomain.com解析到服务器IP地址。dig MX yourdomain.com命令验证MX记录是否生效。adduser命令创建系统用户,或通过MySQL数据库管理虚拟用户(适用于多用户场景)。