在Linux系统中开启SMTP服务器是搭建邮件服务的关键步骤,常用于网站通知、事务邮件等场景,以下是基于Postfix(Linux最常用的邮件传输代理)的详细操作流程,兼顾安全性与易用性,所有命令需以root
权限执行。
sudo apt update && sudo apt upgrade # Debian/Ubuntu
sudo yum update # CentOS/RHEL
**检查主机名**
确保主机名解析正确(邮件服务依赖域名):
```bash
hostname -f # 输出应为完整域名(如 mail.example.com)
若未设置,编辑/etc/hostname
和/etc/hosts
文件。
安装与配置Postfix
安装Postfix
sudo apt install postfix mailutils # Debian/Ubuntu sudo yum install postfix cyrus-sasl-plain # CentOS/RHEL
安装过程中选择 “Internet Site”,并输入邮件域名(如 example.com
)。
基础配置
编辑主配置文件:
sudo nano /etc/postfix/main.cf
修改以下参数:
myhostname = mail.example.com # 服务器完整域名 mydomain = example.com # 邮件域名 myorigin = $mydomain # 外发邮件域名 inet_interfaces = all # 监听所有网络接口 mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain relayhost = # 留空(直接发送邮件)
启动服务
sudo systemctl restart postfix sudo systemctl enable postfix
测试SMTP服务
本地发送测试邮件
echo "Test email body" | mail -s "SMTP Test" your-email@example.com
检查邮件是否送达(查看收件箱或垃圾箱)。
使用Telnet手动测试
telnet localhost 25
依次输入(替换your-email@example.com
):
EHLO localhost MAIL FROM: test@example.com RCPT TO: your-email@example.com DATA Subject: Telnet Test This is a manual SMTP test. . # 单独一行输入英文句点结束 QUIT
安全加固(必做步骤)
防火墙放行SMTP
sudo ufw allow 25/tcp # 开放SMTP端口 sudo ufw allow 587/tcp # 提交端口(TLS加密)
启用SASL认证(防未授权转发)
安装SASL工具:
sudo apt install libsasl2-modules # Debian/Ubuntu sudo yum install cyrus-sasl-plain # CentOS/RHEL
编辑SASL配置:
sudo nano /etc/postfix/sasl/smtpd.conf
添加:
pwcheck_method: auxprop auxprop_plugin: sasldb mech_list: PLAIN LOGIN
创建认证用户:
sudo saslpasswd2 -c -u `postconf -h mydomain` username # 按提示设置密码 sudo chown postfix /etc/sasldb2 # 授权Postfix访问
在main.cf
中启用认证:
smtpd_sasl_auth_enable = yes smtpd_sasl_security_options = noanonymous smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination
配置TLS加密(Let’s Encrypt证书示例)
安装Certbot:
sudo apt install certbot # Debian/Ubuntu sudo yum install certbot # CentOS/RHEL
申请证书:
sudo certbot certonly --standalone -d mail.example.com
在main.cf
中启用TLS:
smtpd_use_tls = yes smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem
常见问题解决
- 邮件被拒收:
检查域名SPF/DKIM记录(需在DNS添加TXT记录),使用工具如dig TXT example.com
验证。 - 端口25被屏蔽:
联系云服务商解封(如AWS、阿里云需提交工单)。 - SASL认证失败:
检查/var/log/mail.log
日志,确认sasldb2
文件权限为640
。 - 高延迟发送:
在main.cf
添加disable_dns_lookups = yes
(关闭反向DNS验证)。
维护建议
- 日志监控:
tail -f /var/log/mail.log # 实时查看邮件日志
- 定期更新:
sudo apt upgrade postfix # Debian/Ubuntu sudo yum update postfix # CentOS/RHEL
- 备份配置:
备份/etc/postfix
目录,避免配置丢失。
引用说明:
- Postfix官方文档:http://www.postfix.org/documentation.html
- Let’s Encrypt证书指南:https://certbot.eff.org/instructions
- SASL配置参考:Cyrus SASL Library Documentation
- 安全实践依据:RFC 3207 (SMTP over TLS), RFC 4954 (SMTP Authentication)
本文基于Ubuntu 22.04/CentOS 7实测,适用于主流Linux发行版。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/9149.html