Search code examples
phpsmtpphpmailer

xampp + PHPMailer + Gmail = SMTP Error: Could not connect to SMTP host


I have installed PHPMailer using Composer and added all the Composer dependency to use Google XOAuth2 authentication. Then I have followed some tutorials to get the refresh token with the Gmail API.
Everything should be working just fine. I did all the paper work right. Right?!

Despite my best intention and all the docs, I'm not able to establish a SMTP connection to smtp.gmail.com

I get this error:

2017-10-20 18:01:45 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP c17sm2715728wrg.26 - gsmtp
2017-10-20 18:01:45 CLIENT -> SERVER: EHLO localhost
2017-10-20 18:01:45 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [151.61.40.58]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-10-20 18:01:45 CLIENT -> SERVER: STARTTLS
2017-10-20 18:01:45 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
SMTP Error: Could not connect to SMTP host.
2017-10-20 18:01:45 CLIENT -> SERVER: QUIT
2017-10-20 18:01:45
2017-10-20 18:01:45
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


My code is straight from the PHPMailer Gmail XOAUTH example.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\OAuth;

use League\OAuth2\Client\Provider\Google;

date_default_timezone_set('Europe/Rome');

require 'lib/php/vendor/autoload.php';

$mail = new PHPMailer;

$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';

$email = 'seckrit-stuff';
$clientId = 'seckrit-stuff';
$clientSecret = 'seckrit-stuff';
$refreshToken = 'seckrit-stuff';

$provider = new Google(
    [
        'clientId' => $clientId,
        'clientSecret' => $clientSecret,
    ]
);
$mail->setOAuth(
    new OAuth(
        [
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,
            'userName' => $email,
        ]
    )
);

$mail->setFrom($email, 'Matteo Bini');
$mail->addAddress('seckrit-stuff', 'Matteo Bini');
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
$mail->CharSet = 'utf-8';
$mail->msgHTML('<strong>HTML</strong> message!');
$mail->AltBody = 'This is a plain-text message body';


if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}


Could you please help me finding a way to use PHPMailer with Gmail in localhost (xampp)?


Solution

  • This is nothing to do with OAuth. You’ve got a much earlier issue at the TLS level. Either you’re missing the openssl extension, it’s misconfigured, or your CA certificates are out of date.

    This issue is covered in the troubleshooting guide the error links to - check using openssl.