Search code examples
phplaraveloauth-2.0phpmailer

SMTP: Could not authenticate with PHPMailer and XOauth2


I am stuck, constantly getting this error from PHPMailer:

"SMTP: Could not Authenticate"

I am using XOAuth2 of PHPMailer. I have tried dump and die on PHPMailer object, it shows the details configured correctly. I have matched refresh token, clientId and clientSecret but they are fine too.

My code is like this:

$phpMailer->SMTPAuth = true;
$phpMailer->SMTPSecure = 'tls';
$phpMailer->SMTPAutoTLS = false;
$phpMailer->Host = 'smtp.gmail.com';
$phpMailer->Port = 587;
$phpMailer->AuthType = 'XOAUTH2';

$path = base_path().'/Modules/Emails/credentials.json';
$credentials = json_decode(file_get_contents($path), true)['web'];

$phpMailer->setOAuth(
  new OAuth(
    [
      'provider' => new Google(
        [
          'clientId' => $credentials['client_id'],
          'clientSecret' => $credentials['client_secret'],
        ]
      ),
      'clientId' => $credentials['client_id'],
      'clientSecret' => $credentials['client_secret'],
      'refreshToken' => $payload->refreshToken,
      'userName' => $payload->from_email,
    ]
  )
);

$phpMailer->setFrom($payload->from_email, "Haider Wain");
$phpMailer->addAddress('haiderwayne.9@gmail.com');
$phpMailer->Subject = 'Test phpmailer';
$phpMailer->CharSet = 'utf-8';
$phpMailer->msgHTML('hello test');
$phpMailer->AltBody = 'This email is HTML; enable HTML mail if you cannot see it.';
$true = $phpMailer->send();

dd($true);

Solution

  • I finally found the solution after 2 days. SMTP is only accepting full access "mail.google.com" for some reason. Any other scope given is rejected. After finding the solution I googled for why this is happening, and this guy explains a bit:

    Using `gmail.send` scope with SMTP MSA