You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPMailer无法连接SMTP服务器:PHP是否有类似Node.js的TLS设置?

问题解决:PHPMailer连接Gmail SMTP失败

先修正代码中的明显错误

  • 主机地址错误:原代码中$mail->Host = 'smtp.google.com;';末尾多了分号,且Gmail的正确SMTP主机是smtp.gmail.com,修正后应为$mail->Host = 'smtp.gmail.com';
  • 拼写错误:addAddress中的收件人名称Reciever拼写错误,改为Receiver(不影响功能,但建议修正)

对应Nodemailer的TLS设置

PHPMailer中可以通过SMTPOptions配置SSL/TLS选项,实现类似Nodemailer中tls.unhandledRejection=false的效果,绕过SSL证书验证相关的错误,代码如下:

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

Gmail认证核心问题

现在Gmail默认开启两步验证,无法直接使用账号密码登录SMTP,必须使用应用专用密码:

  1. 登录Google账号,进入「安全」设置
  2. 找到「应用专用密码」(需先开启两步验证)
  3. 选择邮件应用和对应设备,生成专用密码后替换代码中的$mail->Password

修改后的完整代码

require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    $mail->SMTPDebug = 2;                                      
    $mail->isSMTP();                                           
    $mail->Host       = 'smtp.gmail.com'; // 修正主机地址
    $mail->SMTPAuth   = true;                            
    $mail->Username   = 'myemail@gmail.com';                
    $mail->Password   = '你的应用专用密码'; // 替换为生成的应用专用密码
    $mail->SMTPSecure = 'ssl';
    $mail->Port       = 465; 

    // 添加SSL/TLS选项,解决连接被强制关闭问题
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

    $mail->setFrom('myemail@gmail.com', 'Sender');           
    $mail->addAddress('hisemail@gmail.com');
    $mail->addAddress('hisemail@gmail.com', 'Receiver');
    $mail->isHTML(true);                                 
    $mail->Subject = 'Subject';
    $mail->Body    = 'HTML message body in <b>bold</b> ';
    $mail->AltBody = 'Body in plain text for non-HTML mail clients';
    $mail->send();
    echo "Mail has been sent successfully!";
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

额外排查建议

  • 如果465端口连接失败,尝试改用TLS端口587:设置$mail->SMTPSecure = 'tls';和$mail->Port = 587;
  • 检查服务器防火墙是否允许出站连接到465/587端口
  • 生产环境建议不要禁用SSL证书验证,确保服务器能正常解析Gmail的SSL证书,避免安全风险

内容的提问来源于stack exchange,提问作者Codeleek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 18:58:35