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

线上服务器PHPMailer连接SMTP失败问题求助

PHPMailer无法连接Gmail SMTP服务器:线上SSL证书验证失败,本地正常

问题描述

我在网站中使用PHPMailer类发送邮件,本地环境运行正常,但部署到线上服务器后出现SMTP连接失败错误。错误日志如下:

2018-05-28 12:03:40 Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array() 2018-05-28 12:03:40 Connection failed. Error #2: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [/home/beesystems/public_html/specs/vendor/phpmailer/phpmailer/src/SMTP.php line 325] 2018-05-28 12:03:40 Connection failed. Error #2: stream_socket_client(): Failed to enable crypto [/home/beesystems/public_html/specs/vendor/phpmailer/phpmailer/src/SMTP.php line 325] 2018-05-28 12:03:40 Connection failed. Error #2: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:465 (Unknown error) [/home/beesystems/public_html/specs/vendor/phpmailer/phpmailer/src/SMTP.php line 325] 2018-05-28 12:03:40 SMTP ERROR: Failed to connect to server: (0) SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

我的代码实现如下:

$mail = new PHPMailer(); 
$mail->IsSMTP(); 
$mail->SMTPAuth = true; 
$mail->SMTPSecure = 'ssl'; 
$mail->Host = "smtp.gmail.com"; 
$mail->Port = 465; 
$mail->Username = \Yii::$app->params['mailer-account']; 
$mail->Password = \Yii::$app->params['mailer-password'];

问题分析

从错误日志里的核心提示ssl3_get_server_certificate:certificate verify failed就能看出问题所在:线上服务器缺少信任Gmail SSL证书所需的CA根证书包,或者服务器的OpenSSL配置无法正确验证证书链。本地环境通常预装了完整的CA证书,所以不会触发这个错误。

解决方案

1. 安装/更新服务器的CA证书包

这是最稳妥的根本解决方法,能修复服务器整体的SSL证书信任问题,不只是针对PHPMailer:

  • 对于Ubuntu/Debian系统,执行命令:
    sudo apt-get update && sudo apt-get install --reinstall ca-certificates
    
  • 对于CentOS/RHEL系统,执行命令:
    sudo yum update ca-certificates
    

2. 手动给PHPMailer指定CA证书路径

如果服务器的CA证书路径不标准,或者更新后仍有问题,可以让PHPMailer直接调用指定的CA证书文件:

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => true,
        'cafile' => '/etc/ssl/certs/ca-certificates.crt', // 常见路径,可根据服务器实际情况调整
        'verify_depth' => 5,
    )
);

你可以用find / -name "ca-certificates.crt"命令在服务器上查找正确的CA证书文件路径。

3. 切换到TLS端口(587)尝试

Gmail的SMTP服务同时支持465(SSL)和587(TLS)端口,有些服务器的防火墙可能封锁了465端口,切换到587试试:
修改代码中的这两行:

$mail->SMTPSecure = 'tls'; 
$mail->Port = 587;

4. 检查Gmail账号的安全设置

  • 如果你的Gmail账号开启了两步验证(2FA),必须使用应用专用密码代替普通密码登录SMTP。
  • 未开启2FA的账号,需要确保允许"不太安全的应用"访问(不过Gmail现在默认关闭该选项,更推荐使用应用专用密码)。
  • 同时确认Gmail设置的「转发和POP/IMAP」页面中,IMAP/SMTP服务已经开启。

5. 临时禁用证书验证(仅测试用,生产环境禁止)

如果只是临时测试,或者以上方法都无法解决,可以临时关闭SSL证书验证,但这会带来安全风险,绝对不要在生产环境使用:

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

内容的提问来源于stack exchange,提问作者Mhmd Backer Shehadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:39:20