PHPMailer using gmail and XOAUTH2: How to automatically get a new refresh token when the current refresh token expires?
P粉207969787
P粉207969787 2024-04-06 10:14:45
0
1
413

I followUsing Gmail with XOAUTH2 (PHPMailer Wiki) andHow to use PHPMailer with Gmail XOAUTH2 to send emails? (Chandan for w3jar.com; May 2019). < /p>

Today, my website was unable to send emails because the refresh token expired.

Then I read the PHPMailer Wiki again and found this:

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

Then select the account I will send emails to.

The new token refresh will be displayed as shown below.

After that I need to copy this refresh token and paste it into 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;
    }
}

This is what I have to do when the token expires.

Gmail doesn't have any notification about refresh token expiration.

This creates problems for people using my site. Until someone contacted me and told me about this problem.

How to automatically obtain the refresh token?

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

Can I use PHP? How can I automate this process?

P粉207969787
P粉207969787

reply all(1)
P粉148434742

Finally, I use two-step verification. Reference: https://www.youtube.com/watch?v= mte7LroYd74&list=LL&index=1&t=2s

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!