如何用PHP结合GMAIL SMTP发邮件?PHPMailer SSL证书验证失败求助
在XAMPP本地环境使用PHPMailer发送Gmail邮件时出现SSL证书验证失败错误,此前通过XAMPP的sendmail功能可正常发送。具体错误信息如下:
SMTP Error: Could not connect to SMTP host. Connection failed. stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed. Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host. Connection failed. stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed.
使用的代码如下:
<?php //Import PHPMailer classes into the global namespace //These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require 'src/Exception.php'; require 'src/PHPMailer.php'; require 'src/SMTP.php'; //Create an instance; passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output $mail->isSMTP(); //Send using SMTP $mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through $mail->SMTPAuth = true; //Enable SMTP authentication $mail->Username = 'myemail@gmail.com'; //SMTP username $mail->Password = 'mypassword'; //SMTP password $mail->SMTPSecure = 'tls'; //Enable implicit TLS encryption $mail->Port = 587; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` //Recipients $mail->setFrom('myemail@gmail.com', 'Mailer'); $mail->addAddress('myemail@gmail.com', 'Joe User'); //Add a recipient //Content $mail->isHTML(true); //Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; }
1. 修复Gmail身份验证方式
Gmail已不再支持普通密码登录SMTP,必须使用应用专用密码或OAuth2验证:
- 若开启两步验证,直接生成应用专用密码替换代码中的
mypassword - 未开启两步验证的用户,需先开启该功能,再生成应用专用密码
2. 解决SSL证书验证问题
XAMPP自带的OpenSSL可能缺少根证书,可通过以下两种方式处理:
方式一:配置CA证书路径
下载Mozilla官方根证书包(cacert.pem),将其放置到XAMPP目录下(如xampp/php/extras/ssl/),然后修改php.ini文件:
openssl.cafile = "C:/xampp/php/extras/ssl/cacert.pem" curl.cainfo = "C:/xampp/php/extras/ssl/cacert.pem"
修改完成后重启XAMPP的Apache服务。
方式二:临时禁用证书验证(仅测试环境使用,生产环境不推荐)
在PHPMailer的服务器设置代码块中添加以下配置:
$mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) );
3. 修正SMTPSecure配置
代码注释已说明端口587对应PHPMailer::ENCRYPTION_STARTTLS,建议将字符串配置改为常量引用,避免拼写问题:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
内容的提问来源于stack exchange,提问作者123 456

