Search code examples
phpoauthgmailphpmailer

PHPMailer using gmail with XOAUTH2: How to auto get a new refresh token when the current refresh token is expired?


I follow Using Gmail with XOAUTH2 (PHPMailer Wiki) and How to Send Emails Using PHPMailer with Gmail XOAUTH2? (Chandan for w3jar.com; May 2019).

Today, my website can't send an email because the refresh token was expired.

Then I read the PHPMailer Wiki again and found this:

enter image description here

So, I need to go to this page and click Google.

enter image description here

Then choose my account that will send an email.

enter image description here

The new token refresh will show like this.

enter image description here

After that, I need to copy this refresh token and past this in my send-email function.

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use League\OAuth2\Client\Provider\Google;

function sendEmail($email, $title, $detail)
{
    try {
        $refreshToken = 'I am here';   //////// I am hereeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

        $mail = new PHPMailer(true);

        //Server settings
        $mail->*ANY*;

        //Create a new OAuth2 provider instance
        $provider = new Google([
            'clientId' => $clientId,
            'clientSecret' => $clientSecret
        ]);

        //Pass the OAuth provider instance to PHPMailer
        $mail->setOAuth(new OAuth([
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,
            'userName' => $senderEmail,
        ]));

        if ($mail->send())  return true;


        return false;
    } catch (\Throwable $th) {
        return null;
    }
}

That is what I have to do when the token expired.

Gmail doesn't have any notice for a refresh token expired.

It's causing problems for people using my site. Until someone contacted me to tell me about this problem.

How to auto get refresh token?

This step needs someone to click on the Google button and then click Gmail account to get a refresh token.

Is it possible with PHP? How can I automate the procedure?


Solution

  • Finally, I am using 2 step verification. ref: https://www.youtube.com/watch?v=mte7LroYd74&list=LL&index=1&t=2s