How to use PHPMailer with XOAUTH2?

PHPMailer is a robust PHP library for sending emails, and OAuth2 is an authentication protocol that enhances security.

This comprehensive guide will walk you through the process of using PHPMailer with OAuth2 for Gmail, allowing you to send authenticated and secure emails.

Table of Contents #

1. Introduction

OAuth2 is an authentication protocol that provides a secure way to access Gmail accounts.

Combining PHPMailer with OAuth2 allows you to send authenticated emails via Gmail, ensuring the confidentiality of your communication.

2. Setting Up a PHP Project

Create a new directory called phpmailer for your PHP project and navigate to it using the command line.

mkdir phpmailer
cd phpmailer

3. Installing PHPMailer & oauth2-google

Install the “phpmailer” and “oauth2-google” via composer inside the phpmailer directory.

 composer require phpmailer/phpmailer league/oauth2-google

4. Move the “get_oauth_token.php”

Move the get_oauth_token.php to the root of the phpmailer folder.

#from this

#to this
get OAuth token PHP file inside the vendor folder
move the get OAuth token PHP file to the root

5. Generate the Google Client ID and Secret for PHPMailer

oauth2-google will not work without the client ID, Secret, and refresh token, so we have to generate these three things. Follow the below steps to generate the Client ID and Secret –

  1. Login to Google Cloud Console

    Go to the Google Cloud Console and login with your Google account.

  2. Create a New Project

    After login to your account, Go to Select a project » New Project » create a new project.
    google cloud console create new project

  3. Select the project and go to the APIs & Services

    Select the project and go to the APIs & Services

  4. Enable the Gmail API

    Enable the Gmail API

  5. Create Credentials

    Create Credentials

  6. Choose Web Application & enter the redirect URL

    Redirect URL will be the location of the get_oauth_token.php
    Choose Web Application & enter the redirect URL

  7. Collect your Client ID and Secret

    Collect your Client ID and Secret

  8. Get your Refresh Token

    Open the get_oauth_token.php in your browser, then add client ID and Secret and then click continue.
    Get your Refresh Token for PHPMailer

6. Creating the Email Script

After generating the “Client-ID“, “Client-Secret“, and refresh token“, here is the PHP code (send_email.php) to send emails:

// Add your Client ID, Secret and Refresh token
$clientID = "654563609574-7f5a4c2ev************";
$clientSecret = "GOCSPX-opn_K************NLMPB";
$refreshToken = "1//0g8Dng2fJk3AuC********NwF-L9IrQVKMzy6t***********sVCDSDEYCW2j8z*****nTYiXO3VzuthW-cico";
$email = '[email protected]';
$receiver_email = '[email protected]'; // Email-address of the recipient of the email

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
use League\OAuth2\Client\Provider\Google;

// Load Composer's autoloader
require 'vendor/autoload.php';

// Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

  $mail->isSMTP(); // 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
  $mail->SMTPDebug = SMTP::DEBUG_SERVER;

  // 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';

  // 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, 'Name of the sender');

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

  $mail->isHTML(true); # Set email format to HTML
  $mail->Subject = "Subject Of the email";
  $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
  $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

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

  // Call the send() method to send the mail.
  echo 'Message has been sent';
catch(Exception $e){
  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";

7. Sending the Email

Run the PHP script using the following command:

php send_email.php

This should output either “Message has been sent” or an error message.

8. Conclusion

By following this guide, you have successfully set up a PHP project to send emails using PHPMailer with OAuth2 for Gmail.

This approach provides a secure method for sending authenticated emails, ensuring the confidentiality of your communication.

Experiment with different features of PHPMailer and OAuth2 to customize and enhance your email sending capabilities based on your application’s requirements.