能用,但默认不发邮件——mail()仅调用本地MTA(如sendmail),PHP 8.4未移除或增强它,仍依赖系统配置,不支持直接连接Gmail/Outlook等外部SMTP。
mail() 函数还能用吗?能用,但默认不发邮件——mail() 只是调用系统本地 MTA(如 sendmail、postfix),PHP 本身不带 SMTP 实现。PHP 8.4 没移除 mail(),也没增强它;它和 PHP 5.6 时代的行为一致:依赖服务器环境配置,不支持直接填邮箱密码或指定 Gmail/Outlook 等外部 SMTP。
mail() 在 php8.4 上经常返回 true 却收不到邮件?这是最常被误解的点:mail() 返回 true 仅表示“成功把信交给本地 MTA”,不代表投递成功、更不代表对方收到。常见原因包括:
sendmail 或 postfix(运行 which sendmail 或 systemctl status postfix 验证)/etc/php.ini 中 sendmail_path 配置错误或为空(例如写成 sendmail_path = /usr/sbin/sendmail -t -i 才正确)From:、Content-Type:),被接收方过滤为垃圾邮件PHPMailer 或 symfony/mailer
绕过 mail() 的系统依赖,直接走 SMTP 是更可靠的选择。以 PHPMailer 为例(v6.9+ 完全兼容 PHP 8.4):
安装:
composer require phpmailer/phpmailer
基础用法(以 Gmail 为例):
$mail = new PHPMailer\PHPMailer\PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@gmail.com';
$mail->Password = 'app-specific-password'; // 注意:不是登录密码,需在 Google 账户里生成应用专用密码
$mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_TLS;
$mail->Port = 587;
$mail->setFrom('your@gmail.com', 'Your Name');
$mail->addAddress('to@example.com');
$mail->Subject = 'Hello from PHP 8.4';
$mail->Body = 'This is an HTML message
';
$mail->isHTML(true);
$mail->send();
} catch (Exception $e) {
error_log("Mailer Error: " . $mail->ErrorInfo);
}
关键注意点:
PHPMailer 默认禁用 allow_url_fopen 相关远程加载,无需额外配置mail(),php8.4 下必须检查的三处配置仅限开发测试或内网可信环境。上线项目不建议。
① 确认 sendmail_path 正确(php --ini 找到 loaded config file,检查):
sendmail_path = "/usr/sbin/sendmail -t-i -f noreply@yourdomain.com"
② 邮件头必须手动构造完整(mail() 不自动补 From):
$headers = "From: noreply@yourdomain.com\r\n" .
"Reply-To: noreply@yourdomain.com\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=UTF-8\r\n";
mail('user@example.com', 'Test', 'Hello', $headers);
③ 检查 SELinux 或防火墙是否拦截(CentOS/RHEL):
sudo setsebool -P httpd_can_sendmail 1 sudo firewall-cmd --permanent --add-service=smtp sudo firewall-cmd --reload
实际生产中,mail() 的不可控性远大于便利性——MTA 配置、日志分散、无失败回调、无法追踪送达状态。哪怕只是发注册验证邮件,也值得花十分钟接入 PHPMailer 或 symfony/mailer。