使用Gmail smtp服务器发送邮件时,PHPMailer会出错

时间:2017-12-13 19:52:35

标签: php email phpmailer

我在自制模板/邮件功能中使用phpmailer:

<?php  
require_once(__DIR__.'/../../vendor/phpmailer/phpmailer/PHPMailerAutoload.php');
function sendTemplateMail($body, $data, $subject, $receiver, $sender){
$template = Timber::compile($body, $data);
sendMail($template, $subject, $receiver, $sender);
}  

function sendMail($template, $subject, $receiver, $sender){

$mail = new PHPMailer(true);                        // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP     // TCP port to connect to

$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "**";
$mail->Password = "**";

$mail->setFrom($sender);
$mail->addAddress($receiver);     // Add a recipient
$mail->addReplyTo($sender);

$mail->isHTML(true);

$mail->Subject = $subject;
$mail->Body = $template;
$mail->AltBody = $template; //$mail->AltBody = $template; //

return $mail->send();
}

在我的项目中,用户名和密码是正确的,因为它们之前有效。但现在我得到一个错误,smtp没有连接。 致命错误:未捕获phpmailerException:SMTP错误:无法连接到SMTP主机。

1 个答案:

答案 0 :(得分:0)

试试这个,将句子添加到sendMail函数:

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

您可以通过允许在PHPMailer的5.2.10推出SMTPOptions财产不安全的连接(这是可能通过继承早期版本的SMTP类来做到这一点),虽然这是不推荐,因为它违背了多至少要使用安全传输。

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#php-56-certificate-verification-failure

这应该是一个临时解决方案。