PHPMailer Google Oauth2 sending email issue

im using php 7.4 with the php libs

{
   "require": {
       "league/oauth2-google": "4.0.0",
       "phpmailer/phpmailer": "6.1.4"
   }
}

here is my php code

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerOAuth;
use LeagueOAuth2ClientProviderGoogle;

date_default_timezone_set('Etc/UTC');

require '/home/automa15/vendor/autoload.php';

session_start();

$email = 'xxx';
$clientId = 'xxx.googleusercontent.com';
$clientSecret = 'xxx';
$redirectUri = 'xxx/oauth2callback.php';
$tokenPath = 'xxx/token.json';

$provider = new Google([
    'clientId' => $clientId,
    'clientSecret' => $clientSecret,
    'redirectUri' => $redirectUri,
    'scopes' => ['https://www.googleapis.com/auth/gmail.send']
]);

function saveTokenToFile($tokenPath, $token) {
    if (!file_put_contents($tokenPath, json_encode($token->jsonSerialize()))) {
        exit('Failed to save the access token');
    }
    echo 'Access token saved successfully<br>';
}

function getTokenFromFile($tokenPath) {
    if (file_exists($tokenPath)) {
        $tokenData = json_decode(file_get_contents($tokenPath), true);
        if (isset($tokenData['access_token']) && isset($tokenData['refresh_token'])) {
            return new LeagueOAuth2ClientTokenAccessToken($tokenData);
        }
    }
    return null;
}

$token = getTokenFromFile($tokenPath);

if (!$token) {
    if (!isset($_GET['code'])) {
        $authUrl = $provider->getAuthorizationUrl([
            'access_type' => 'offline',
            'prompt' => 'consent',
        ]);
        $_SESSION['oauth2state'] = $provider->getState();
        echo '<script>window.location.replace("' . $authUrl . '");</script>';
        exit;
    } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
        exit('Invalid state');
    } else {
        // Try to get an access token using the authorization code
        try {
            $token = $provider->getAccessToken('authorization_code', [
                'code' => $_GET['code']
            ]);
            if ($token->getRefreshToken()) {
                saveTokenToFile($tokenPath, $token);
                echo 'Token obtained and saved<br>';
            } else {
                exit('Failed to obtain refresh token');
            }
            echo '<script>window.location.replace("' . $_SERVER['PHP_SELF'] . '");</script>';
            exit;
        } catch (Exception $e) {
            exit('Failed to get access token: ' . $e->getMessage());
        }
    }
} else {
    // Refresh the token if it has expired
    if ($token->hasExpired()) {
        try {
            $token = $provider->getAccessToken('refresh_token', [
                'refresh_token' => $token->getRefreshToken()
            ]);
            saveTokenToFile($tokenPath, $token);
            echo 'Token refreshed successfully<br>';
        } catch (Exception $e) {
            exit('Failed to refresh access token: ' . $e->getMessage());
        }
    }
}

if (!$token->getRefreshToken()) {
    exit('No refresh token found in the access token');
}

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

$t = $token->getRefreshToken();

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

$mail->setFrom($email, 'Soul of Tanzania');
$mail->addAddress('xxx', 'John Doe');
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML("aaa");
$mail->AltBody = 'This is a plain-text message body';

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

?>

this is the code for oauth2callback.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

use LeagueOAuth2ClientProviderGoogle;
require '/home/automa15/vendor/autoload.php';

session_start();

$email = 'xxx';
$clientId = 'xxx.googleusercontent.com';
$clientSecret = 'xxx';
$redirectUri = 'xxx/oauth2callback.php';
$tokenPath = 'xxx/token.json';

$provider = new Google([
    'clientId' => $clientId,
    'clientSecret' => $clientSecret,
    'redirectUri' => $redirectUri,
    'scopes' => ['https://www.googleapis.com/auth/gmail.send'],
    'accessType' => 'offline',
    'prompt' => 'consent',
]);

if (!isset($_GET['code'])) {

    $authorizationUrl = $provider->getAuthorizationUrl([
        'access_type' => 'offline',
        'prompt' => 'consent',
    ]);

    $_SESSION['oauth2state'] = $provider->getState();

    $_SESSION['oauth2pkceCode'] = $provider->getPkceCode();

    header('Location: ' . $authorizationUrl);
    exit;

} elseif (empty($_GET['state']) || empty($_SESSION['oauth2state']) || $_GET['state'] !== $_SESSION['oauth2state']) {

    if (isset($_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
    }

    exit('Invalid state');

} else {

    try {
    
        // Try to get an access token using the authorization code grant.
        $accessToken = $provider->getAccessToken(
            'authorization_code',
            [
                'code' => $_GET['code']
            ]
        );

        echo 'Access Token: ' . $accessToken->getToken() . "<br>";
        echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
        echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
        echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";

        $tokenPath = 'xxx/token.json';
        $tokenData = [
            'access_token' => $accessToken->getToken(),
            'refresh_token' => $accessToken->getRefreshToken(),
            'expires' => $accessToken->getExpires(),
            'resource_owner_id' => $accessToken->getResourceOwnerId(),
        ];
        if (!file_put_contents($tokenPath, json_encode($tokenData))) {
            exit('Failed to save the access token');
        }
        echo 'Tokens obtained and saved to token.json';

    } catch (LeagueOAuth2ClientProviderExceptionIdentityProviderException $e) {

        // Failed to get the access token or user details.
        exit($e->getMessage());

    }

}
?>

i have done all, less secure app ON, and code is all working if i switch to user and password but issue in Oauth2 and this is the error im getting, cna anyone help, this is becoming a torture.

```

2024-05-23 14:23:18 Connection: opening to smtp.gmail.com:587, timeout=300, options=array()
2024-05-23 14:23:18 Connection: opened
2024-05-23 14:23:19 SMTP INBOUND: “220 smtp.gmail.com ESMTP d9443c01a7336-1ef0c036347sm257008095ad.203 – gsmtp”
2024-05-23 14:23:19 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP d9443c01a7336-1ef0c036347sm257008095ad.203 – gsmtp
2024-05-23 14:23:19 CLIENT -> SERVER: EHLO www.souloftanzania.com
2024-05-23 14:23:19 SMTP INBOUND: “250-smtp.gmail.com at your service, [75.119.223.127]”
2024-05-23 14:23:19 SMTP INBOUND: “250-SIZE 35882577”
2024-05-23 14:23:19 SMTP INBOUND: “250-8BITMIME”
2024-05-23 14:23:19 SMTP INBOUND: “250-STARTTLS”
2024-05-23 14:23:19 SMTP INBOUND: “250-ENHANCEDSTATUSCODES”
2024-05-23 14:23:19 SMTP INBOUND: “250-PIPELINING”
2024-05-23 14:23:19 SMTP INBOUND: “250-CHUNKING”
2024-05-23 14:23:19 SMTP INBOUND: “250 SMTPUTF8”
2024-05-23 14:23:19 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [75.119.223.127]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2024-05-23 14:23:19 CLIENT -> SERVER: STARTTLS
2024-05-23 14:23:19 SMTP INBOUND: “220 2.0.0 Ready to start TLS”
2024-05-23 14:23:19 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2024-05-23 14:23:20 CLIENT -> SERVER: EHLO www.souloftanzania.com
2024-05-23 14:23:20 SMTP INBOUND: “250-smtp.gmail.com at your service, [75.119.223.127]”
2024-05-23 14:23:20 SMTP INBOUND: “250-SIZE 35882577”
2024-05-23 14:23:20 SMTP INBOUND: “250-8BITMIME”
2024-05-23 14:23:20 SMTP INBOUND: “250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH”
2024-05-23 14:23:20 SMTP INBOUND: “250-ENHANCEDSTATUSCODES”
2024-05-23 14:23:20 SMTP INBOUND: “250-PIPELINING”
2024-05-23 14:23:20 SMTP INBOUND: “250-CHUNKING”
2024-05-23 14:23:20 SMTP INBOUND: “250 SMTPUTF8”
2024-05-23 14:23:20 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [75.119.223.127]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2024-05-23 14:23:20 Auth method requested: XOAUTH2
2024-05-23 14:23:20 Auth methods available on the server: LOGIN,PLAIN,XOAUTH2,PLAIN-CLIENTTOKEN,OAUTHBEARER,XOAUTH
2024-05-23 14:23:21 CLIENT -> SERVER: AUTH XOAUTH2 dXNlcj1pbmZvQHNvdWxvZnRhbnphbmlhLmNvbQFhdXRoPUJlYXJlciB5YTI5LmEwQVhvb0NndkdUcXJHNnlwNTlIanZCd0xSaDRzNnpTdDFiWENXZmJTYkl4YUluekJXMFRQcnVkOXpEcEZoYm9RN2VKSGt4UmNSUGFhVDhfSDJQekw0WFJVMENHbjRpT0hPOUplanV5Y25KZFBqUVp0dTk3ZVF5TVdzRVdVRi1lSHBoUHdDTXlnT05zdEwyel9DUzIyZk1Xak9oRE5COERfdlZzM2VhQ2dZS0FlMFNBUThTRlFIR1gyTWk2dTR5Zk14M3pNVENFWTFGclR0aDJ3MDE3MQEB
2024-05-23 14:23:21 SMTP INBOUND: “334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==”
2024-05-23 14:23:21 SERVER -> CLIENT: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
2024-05-23 14:23:21 SMTP ERROR: AUTH command failed: 334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
SMTP Error: Could not authenticate.
2024-05-23 14:23:21 CLIENT -> SERVER: QUIT
2024-05-23 14:23:21 SMTP INBOUND: “535-5.7.8 Username and Password not accepted. For more information, go to”
2024-05-23 14:23:21 SMTP INBOUND: “535 5.7.8 https://support.google.com/mail/?p=BadCredentials d9443c01a7336-1ef0c036347sm257008095ad.203 – gsmtp”
2024-05-23 14:23:21 SERVER -> CLIENT: 535-5.7.8 Username and Password not accepted. For more information, go to535 5.7.8 https://support.google.com/mail/?p=BadCredentials d9443c01a7336-1ef0c036347sm257008095ad.203 – gsmtp
2024-05-23 14:23:21 SMTP ERROR: QUIT command failed: 535-5.7.8 Username and Password not accepted. For more information, go to535 5.7.8 https://support.google.com/mail/?p=BadCredentials d9443c01a7336-1ef0c036347sm257008095ad.203 – gsmtp
2024-05-23 14:23:21 Connection: closed
SMTP Error: Could not authenticate.

Fatal error: Uncaught PHPMailerPHPMailerException: SMTP Error: Could not authenticate. in /home/automa15/vendor/phpmailer/phpmailer/src/PHPMailer.php:2024 Stack trace: #0 /home/automa15/vendor/phpmailer/phpmailer/src/PHPMailer.php(1844): PHPMailerPHPMailerPHPMailer->smtpConnect(Array) #1 /home/automa15/vendor/phpmailer/phpmailer/src/PHPMailer.php(1587): PHPMailerPHPMailerPHPMailer->smtpSend(‘Date: Thu, 23 M…’, ‘This is a multi…’) #2 /home/automa15/vendor/phpmailer/phpmailer/src/PHPMailer.php(1423): PHPMailerPHPMailerPHPMailer->postSend() #3 /home/automa15/souloftanzania.com/backoffice/addPayment2.php(138): PHPMailerPHPMailerPHPMailer->send() #4 {main} thrown in /home/automa15/vendor/phpmailer/phpmailer/src/PHPMailer.php on line 2024


tried all the solution so far, but no clue what is missing or wrong here

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật