How to Send Emails Using PHPMailer with Gmail XOAUTH2?

In this post, you will learn how to send emails using PHPMailer with Gmail XOAUTH2, and you can also send emails from localhost.

PHPMailer send emails with Gmail XOAUTH2

1. Create the application folder.

First, start your local server and go to the XAMPP htdocs folder or whatever you are using. In the htdocs folder, create a new folder for the application and name it whatever you want, I named it phpmailer.

phpmailer app folder

2. Install the PHPMailer and oauth2-google.

Now inside the application folder (in my case it is phpmailer folder), Install the PHPMailer and oauth2-google through the composer, but if you do not have the Composer, install it first.

composer require phpmailer/phpmailer
composer require league/oauth2-google

3. Get the google client id and secret.

Now you have to generate the google client id and secret, and for this go to the Google Developers Console and login with your Google account.

1. After login to your account click on the Select a project.

select a project on Google Developers Console

2. If you don’t have any project then create a new project.

create new project on Google Developers Console

3. Enter the Project name and click Create.

enter project name

4. After that go the APIs & Services and enable the Gmail API.

Google Developers Console APIs and Services
Enable Gmail API

5. Now you need to create Credentials, and for this click on the CREATE CREDENTIALS button.

Google Developers Console Create Credentials

6. Select the Gmail API and User data, then click Next.

Select Gmail API and user data

7. Enter your App name and email, then click SAVE AND CONTINUE.

Enter app name and your mail

8. In the Scope section you don’t have to do anything, just click SAVE AND CONTINUE.

save and continue

9. Now choose the Application Type which is Web application and enter the Name.

Application Type is Web Application

10. Now enter the URL path of the get_oauth_token.php in the Authorized redirect URLs and click on the CREATE.

Authorized redirect urls
Path of get_oauth_token.php

After that, click on the Done then click on the client that you created, and you will find the client id and secret.

Done button
Oauth 2.0 Client IDs
Google Client ID and Secret

After getting the Client ID and secret, you have to publish your app.

So go to the OAuth consent screen and publish your app.

Oauth Consent SCreen
Publish App

4. Get the Refresh Token.

To get the Refresh Token, open the get_oauth_token.php in your editor, then –

Fix the autoload.php path.

Fix autoload.php path

Change the client id and secret into yours.

Set the Client id and secret

Now open the get_oauth_token.php URL in your browser and choose Google.

Run the get_oauth_token.php and choose google

After that, login with your google account.

login with your google account

Allow the Gmail permission.

Allow Gmail permission

Now you will be redirected to your localhost, and you will find the Refresh token. Copy the refresh token and save it elsewhere.

copy the refresh token

But if you face the Google hasn’t verified this app Error, then Go to your app with the Unsafe.

5. PHPMailer send emails with Gmail XOAUTH2

Now you have got the Client ID, Secret, and Refresh Token.

So then, in the root of the app folder create index.php file.

In the follwing index.php you have to change the email, client ID, Secret, Refresh Token, Receiver email in to yours.


 * This example shows how to send via Google's Gmail servers using XOAUTH2 authentication.

//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that

//Load dependencies from composer
//If this causes an error, run 'composer install'
require 'vendor/autoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer();

//Tell PHPMailer to use SMTP

//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages

//Set the hostname of the mail server
$mail->Host = '';

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption mechanism to use - STARTTLS or SMTPS

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';

//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = '[email protected]';
$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';

//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'your_refresh_token';

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

//Pass the OAuth provider instance to PHPMailer
    new OAuth(
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,
            'userName' => $email,

//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'Sender Name');

//Set who the message is to be sent to
$mail->addAddress('[email protected]');

// if you want to send email to multiple users, then add the email addresses you which you want to send.
//$mail->addAddress('[email protected]');
//$mail->addAddress('[email protected]');


//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';

$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

//Replace the plain text body with one created manually
// $mail->AltBody = 'This is a plain-text message body';

//For Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz');  // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // You can specify the file name

//send the message, check for errors
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';

After that open the index.php in your browser, and then check your email.

Done 😃

Leave a Reply