How To Use PHPMailer With XOAUTH2

We have already seen how to send email using PHPMailer but that time we used generated app password. But in this tutorial you will learn how to use PHPMailer with XOAUTH2 which is an authentication protocol that enhances security.

What is OAuth2

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.

Steps to Use PHPMailer with XOAUTH2

Step 1: Setting Up a PHP Project

Open your xampp htdocs folder or localhost www directory and create a new folder called phpmailer this is the application or project folder.

mkdir phpmailer
cd phpmailer

Step 2: Install the PHPMailer and oauth2-google

Now in the the phpmailer folder, install the “phpmailer” and “oauth2-google” libraries via composer.

 composer require phpmailer/phpmailer league/oauth2-google

Step 3: Move the “get_oauth_token.php” to the Root

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

#from this
phpmailer/vendor/phpmailer/phpmailer/get_oauth_token.php

#to this
phpmailer/get_oauth_token.php
get OAuth token PHP file inside the vendor folder
move the get OAuth token PHP file to the root

Step 4: 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. Go to the Google Cloud Console and login with your Google account.
  2. After login to your account, Go to Select a project » New Project » create a new project.
create a new project in google cloud console
  1. Select the project and go to the “APIs & Services”.
Select the project and go to the APIs & Services.
  1. Go to the Enable API and Service » Enable the Gmail API » Create Credentials.
enable gmail api in google cloud console
  1. Create Credentials.
Create Credentials for gmail oauth 2
  1. Choose Web Application & enter the redirect URL. The redirect URL will be the location of the get_oauth_token.php.
create credentials add authorized redirect uris
  1. Collect your Client ID and Secret.
Collect your google Client ID and Secret
  1. To Get your Refresh Token open the get_oauth_token.php in your browser, then add client ID and Secret and then click continue. After getting your refresh token copy and save it.
http://localhost/phpmailer/get_oauth_token.php
generate your refresh token for gmail xoauth2

Step 5: Create Email Sending Script

After generating the “Client-ID”, “Client-Secret”, and “refresh token”, create a new PHP file called send_email.php at the root and put the following code into this file. Read the comments to understand the code and change the details according to yours.

<?php
// Add your Client ID, Secret and Refresh token
$clientID = "654563609574-7f5a4c2ev************99m0i1.apps.googleusercontent.com";
$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);

try{
  $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 = 'smtp.gmail.com';
  
  // 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
  $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

  // 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
  $mail->setOAuth(
    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');

  $mail->addAddress($receiver_email);
  /* 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.
  $mail->send();
  echo 'Message has been sent';
}
catch(Exception $e){
  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Step 6: Test the Email Sending Script

Run the PHP script using the following command or you can run the script via browser:

php send_email.php

OR

http://localhost/phpmailer/send_email.php

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


Thank You 🙏. If you have any question leave in the comment box 💬.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy