排查 PHP 邮件发送失败,优先检查 SMTP 连接超时与认证错误。若使用 PHPMailer,确保配置了正确的 Host、Port、Username 和 Password,并开启 SMTPDebug 查看具体报错。

SMTP 连接超时原因分析
SMTP 连接超时通常由网络防火墙拦截、服务器端口未开放或 DNS 解析缓慢引起。需确认目标邮件服务商(如 QQ 邮箱、Gmail)的 SMTP 地址与端口是否匹配。

常见端口为 25(明文)、465(SSL)或 587(TLS)。若服务器环境限制了出站连接,会导致 fsockopen 或 stream_socket_client 超时。建议先通过命令行测试连通性,再调整代码中的 Timeout 设置。
PHPMailer 完整实现与认证调试
以下代码展示了使用 PHPMailer 发送带附件邮件的标准流程,包含必要的异常捕获与调试输出。将代码保存为 send_mail.php 并在本地或服务器运行。

<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
try {
$mail = new PHPMailer(true);
// 启用 SMTP 调试,级别 2 显示收发信息
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.example.com'; // 替换为你的 SMTP 主机
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com'; // 替换为你的用户名
$mail->Password = 'your_password'; // 替换为你的密码或授权码
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 或 ENCRYPTION_SMTPS
$mail->Port = 587; // 对应 TLS 端口
$mail->setFrom('from@example.com', 'Sender Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Test Subject';
$mail->Body = '<h1>Hello World</h1><p>This is a test email.</p>';
$mail->send();
echo 'Message sent successfully!';
} catch (Exception $e) {
echo "Mailer Error: {$mail->ErrorInfo}";
}
运行程序后,若控制台输出 220 开头且无红色错误,表示连接成功。若出现 Connection timed out,需检查网络防火墙;若出现 Authentication failed,请核对账号密码或启用授权码。预期结果为页面显示 “Message sent successfully!”。
代码中使用了 SMTPDebug 级别 2,可在浏览器直接看到握手过程。若遇到认证失败,请检查是否开启了邮箱的“授权码”功能而非登录密码。
SMTPAuthError` 与 SSL/TLS 证书验证
当出现 SMTPAuthError 时,多数情况是密码错误或未启用应用专用密码。若连接 465 端口却未启用 SMTPSecure = 'ssl',会引发协议不匹配错误。
部分 Linux 服务器缺少根证书包,导致 SSL 握手失败。需在 php.ini 中指定 openssl.cafile,或在代码中临时设置 $mail->SMTPOptions = ['ssl' => ['verify_peer' => false]] 进行排查(生产环境不建议关闭验证)。