在 Ubuntu LNMP 环境中配置邮件服务
一 目标与方案选择
- 目标通常分为两类:
- 让 PHP 的 mail() 函数可用(网站注册、找回密码等站内信)。
- 搭建完整的 SMTP/IMAP/POP3 邮件服务器(可选,用于收发邮件)。
- 方案建议:
- 仅站内邮件:安装本地 MTA(Postfix 或 Sendmail)+ 配置 PHP 的 sendmail_path。
- 完整邮件服务器:安装 Postfix + Dovecot + SASL,并正确配置 DNS 记录 与 TLS。
- 基础准备:一台可公网访问的 Ubuntu 服务器、已解析的 域名、开放 25/587/465/993/995 端口(云厂商安全组与防火墙需放行)。
二 方案一 快速启用 PHP mail 函数(站内邮件)
- 安装组件(二选一,推荐 Postfix;若已装 Sendmail 也可继续用):
- sudo apt update && sudo apt install postfix
- 或 sudo apt install sendmail
- 配置 PHP(路径随 PHP 版本/安装方式不同,常见如下):
- 系统 PHP:编辑 /etc/php/*/fpm/php.ini,确保
sendmail_path = /usr/sbin/sendmail -t -i
- 一键包或编译 PHP:编辑 /usr/local/php/etc/php.ini,同样设置
sendmail_path = /usr/sbin/sendmail -t -i
- 重启服务:
- sudo systemctl restart php-fpm*
- 若使用 Sendmail:sudo systemctl restart sendmail
- 测试脚本(/var/www/html/mail_test.php):
<?php
$to = 'you@example.com';
$subject = 'LNMP mail() 测试';
$message = '这是一封来自 LNMP 环境的测试邮件。';
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com\r\nX-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $headers)) {
echo "发送成功";
} else {
echo "发送失败";
}
访问 http://服务器IP/mail_test.php 查看结果。
- 一键包环境提示:若使用 lnmp.org 一键包,常见 php.ini 路径为 /usr/local/php/etc/php.ini,修改后执行 /root/lnmp restart 或重启 php-fpm 生效。
三 方案二 搭建完整邮件服务器 Postfix + Dovecot + SASL(可选)
- 安装软件:
- sudo apt install postfix dovecot-core dovecot-imapd dovecot-pop3d
- 安装 SASL 认证组件:sudo apt install libsasl2-modules sasl2-bin
- 基础 Postfix 配置(/etc/postfix/main.cf,按需调整域名):
- myhostname = mail.example.com
- mydomain = example.com
- myorigin = $mydomain
- inet_interfaces = all
- mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
- home_mailbox = Maildir/
- 启用 SMTP 身份验证(SASL/TLS):
- 创建/编辑 /etc/postfix/sasl/smtpd.conf:
pwcheck_method: saslauthd
mech_list: plain login
- 编辑 /etc/default/saslauthd:MECHANISMS=“pam”
- 启动 SASL:sudo systemctl start saslauthd && sudo systemctl enable saslauthd
- 在 /etc/postfix/master.cf 的 smtp inet 段添加:
-o smtpd_sasl_auth_enable=yes
-o smtpd_sasl_type=cyrus
-o smtpd_sasl_path=smtpd
-o smtpd_tls_security_level=may
- 重载 Postfix:sudo postfix reload
- Dovecot 基础配置(/etc/dovecot/dovecot.conf 或 /etc/dovecot/conf.d/10-mail.conf):
- mail_location = maildir:/home/%u/Maildir(或系统合适路径)
- 启用 IMAP/POP3:protocols = imap pop3(可按需启用 ssl)
- 启动 Dovecot:sudo systemctl restart dovecot
- DNS 记录示例(将 example.com 与 1.2.3.4 替换为你的域名与服务器 IP):
- MX @ → example.com(优先级 10)
- A mail → 1.2.3.4
- A smtp → 1.2.3.4
- A imap → 1.2.3.4
- A pop3 → 1.2.3.4
完成后可用邮件客户端测试 SMTP/IMAP/POP3 的登录与收发。
四 常见问题与排查
- 邮件进垃圾箱:配置 SPF、DKIM、DMARC 记录,使用有效发信域名与固定 HELO/EHLO 主机名,避免动态 IP 与开放中继。
- 端口被封:云厂商常限制 25 端口出站,改用 587(Submission,STARTTLS) 或 465(SMTPS);同时确保 993/995 入站放行。
- 认证失败:确认 SASL 服务运行、Postfix 的 smtpd_sasl_auth_enable=yes 与 smtpd_tls_security_level 设置正确。
- PHP mail() 失败:核对 php.ini 中 sendmail_path 与 php-fpm 已重启;查看 /var/log/mail.log 与 /var/log/syslog 的错误信息。
- 一键包环境差异:若 php.ini 在 /usr/local/php/etc/php.ini,修改后需重启 php-fpm 或执行 /root/lnmp restart 生效。