简体   繁体   中英

PHPMailer gives an error when sending mails with the Gmail smtp server

I'm using phpmailer in a selfmade template/mail function:

<?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();
}

In my project the username and password are correct because they worked before. But now I get an error that the smtp is not connected. fatal error: Uncaught phpmailerException: SMTP Error: Could not connect to SMTP host.

Try this, add the sentence to sendMail function:

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

You can allow insecure connections via the SMTPOptions property introduced in PHPMailer 5.2.10 (it's possible to do this by subclassing the SMTP class in earlier versions), though this is not recommended as it defeats much of the point of using a secure transport at all.

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

This should be a temporary solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM