Search code examples
phpmailer

PHPMailer + smtp.gmail.com : Could not connect to SMTP host


I was trying to use PHPMailer library to send email. I installed PHPMailer using composer And i just use their tutorial example. Before that I also set the gmail account settings to allow less secure apps. Here is my code:

<?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\Exception;
//Load Composer's autoloader
require 'phpmailer/vendor/autoload.php';
$mail = new PHPMailer(true);                 // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                    // Enable verbose debug output
    $mail->isSMTP();                         // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com:587';      // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                  // Enable SMTP authentication
    $mail->Username = '[email protected]';    // SMTP username
    $mail->Password = 'hidden';              // SMTP password
    $mail->SMTPSecure = 'tls';               // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                       // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Mr. From');
    $mail->addAddress('[email protected]', 'Mr. To');   // 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;
}

?>

And Here is the Error:

2018-03-30 05:44:49 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP 5sm16638786pfh.133 - gsmtp
2018-03-30 05:44:49 CLIENT -> SERVER: EHLO localhost
2018-03-30 05:44:50 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [123.244.104.122]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2018-03-30 05:44:50 CLIENT -> SERVER: STARTTLS
2018-03-30 05:44:50 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
SMTP Error: Could not connect to SMTP host.
2018-03-30 05:44:50 CLIENT -> SERVER: QUIT
2018-03-30 05:44:50
2018-03-30 05:44:50
SMTP Error: Could not connect to SMTP host.
Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host.

Please help me.


Solution

  • Just Add the following codes before line code $mail->SMTPDebug saves the day

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