How to use PHPMailer, after 30 May 2022 when "Less secure app" is no longer an option?
Asked Answered
P

5

11

I have been using PHPMailer for a long time to send emails using Google credentials (login and password) by enabling the "Less secure app" option in the Google settings.

As Google is notifying that after 30th May 2022, Google will not allow sending emails using the "Less secure app".

Less secure apps & your Google Account

enter image description here

Is there any other way to send emails using Gmail SMTP from PHPMailer without the "Less secure app" feature?

Peptic answered 4/5, 2022 at 13:17 Comment(0)
K
8

This ways work for me, you can try this :

  1. First go to your google account management and go to security.
  2. Make sure your 2-step verification are enabled.
  3. Then go to app password.
  4. Select other in the select app dropdown menu, and named whatever you like.
  5. And click generate, google will give you a password. make sure you copy it and save it somewhere else.
  6. instead using your real google account password in PHPMailer setting, use the password you just generate.
Kelly answered 18/7, 2022 at 12:9 Comment(3)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Lombardi
This is the correct answer. It is laid out step-by-step and works perfectly! After hours of trying to do this, I came across your response and was up-and-running in minutes. Thanks!Monserratemonsieur
That "select Other and name it whatever you want" was extremely helpful in my case. And you cannot find that password after it is shown once. In that case creating new one is easy enough though.Graphomotor
K
5

What you need to do is switch to XOAUTH2 or to the Gmail API again using Oauth2.

$mail->oauthUserEmail = "[Redacted]@gmail.com";
$mail->oauthClientId = "[Redacted]";
$mail->oauthClientSecret = "[Redacted]";
$mail->oauthRefreshToken = "[Redacted]";

You can't send email with out the users permission. The owner of the gmail account you are trying to send mails from will need to authorize the app once if you store the refresh token you should be able to use it without any issues.

Remember you will need to go though the application verification process with google. As you will be using a sensitive scope.

Using their login and password is no longer an option.

Kailyard answered 4/5, 2022 at 18:11 Comment(4)
How long does the token last?Resuscitator
refresh token will last seven days until your app has been set into production. Then it will no longer expireKailyard
Is it a free service or is there any limit on send emails?Pompano
its free to send emails any limit would be the same limit applied by gmail itself.Kailyard
D
1

No need to worry about google, less secure apps function.

Step 1. Open a browser and go to google account management. (Not Gmail)

Step 2. Select security in the list, left side of screen.

Step 3. After selecting security make sure 2-step verification is enabled. (middle of screen)

Step 4. Select App passwords (below 2-step verification) and enter your normal password to continue.

Step 5. Under Select the app and device you want to generate the app password for, click the select app drop down arrow and click on, other (custom name)

Step 6. Enter a name for the app, printer etc... and click on generate for your new password. Use the password generated for the app, printer etc.. that you are trying to use due to google shutting down less secure apps function.

(Your regular password will continue to function for Gmail, and Google Account Management)

RB

Drafty answered 5/10, 2022 at 13:50 Comment(0)
P
1

For Reference please visit the GitHub on:

  [https://github.com/shahhussain305/esdn_classes][1]
  
  /*
  To use this new method of PHPMailer follow the following steps on 
  ubuntu:
Step 1: Install Composer
    $   sudo apt update
        sudo apt install php-cli unzip
    $   cd ~
    $   curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
    $   HASH=`curl -sS https://composer.github.io/installer.sig`
    $   php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
        Output: Installer verified
    **Note**: If the output says Installer corrupt, you’ll need to repeat the download and verification process until you have a verified installer.
*   The following command will download and install Composer as a system-wide command named composer, under /usr/local/bin:
$   sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer
Output
All settings correct for using Composer
Downloading...
Composer (version 2.3.5) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
To test your installation, run:
$   composer

Step 2: Go to your website root directory and Run the following command

$   composer require phpmailer/phpmailer
*/ 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

class Communicator{ 
    /* to send emails from your registered domain / hosting email server
    private $host = "smtp.hostinger.com";
    private $userName="[email protected]";
    private $robots = array(
                        '[email protected]',
                        '[email protected]',
                        '[email protected]',
                        '[email protected]',
                        '[email protected]');
    private $password="jashdf &_isdf807%^$^sdf;_sdf*)465";
    public $from_email='[email protected]';
    */
    //----------Send Email From GMAIL SMTP Server -----------------//
    /*
     To activate sending emails from gmail, please do the following:
     1- login to your gmail account and go to the manage accounts (Top right under the user name logo)
     2- click on the security (left side menus)
     3- Activate the two step varification
     4- under the two step varification, click on the app password, click on the first dropdwon and select Custom name and Type any name like PHPMailer etc
     */
    private $host = "smtp.gmail.com";
    private $userName="[email protected]";
    private $password="ywhstefdirkdfhen";
    private $robots = array(
                        array('[email protected]','ywhstefdirkdfhen'),
                        array('[email protected]','oejrgdbeygswjhdo'),
                        array('[email protected]','poswkfhrusnfhwlv'),
                        array('[email protected]','tgfdeswavfgdertk'),
                        array('[email protected]','polkhytrdwesaqzx'),
                        array('[email protected]','okljuhbgtrdfcxse')
                        );

    public $from_email='[email protected]';
    //------------------------------------------------------//
    public $replyTo="[email protected]";
    var $tempVar;
    public $from_name = 'NAME OF YOUR ORGANIZATION';
    public $charSet = "CharSet = 'UTF-8'";
    public $charSetOpt = 0;
    //function to send email simple and with attachements
    
  public function sendEmail($to,$from,$sender_name="",$subject,$body,$attachement_path="",$cc="",$bcc=""){ 
        require '../../../../vendor/autoload.php';      
        $mail = new PHPMailer;
        $mail->IsSMTP();            // set mailer to use SMTP i.e. 
        smtp1.example.com;smtp2.example.com
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->Host = $this->host;  // specify main and backup server
        $mail->SMTPAuth = true;     // turn on SMTP authentication
        $mail->Username = $this->userName;  // SMTP username i.e email id of an email address
        $mail->Password = $this->password; // SMTP password for the specified email address         
        $mail->Port = 587;
        $mail->SMTPSecure = 'tls';
                    if($this->charSetOpt != 0){
                       $mail->CharSet = $this->charSet;
                    }
        $mail->From = $from;
        $mail->FromName = $sender_name;
        $mail->addAddress($to);   //mail,name
        if(isset($cc) && !empty($cc)){
            $mail->addBCC($bcc);
            }
        if(isset($cc) && !empty($cc)){
            $mail->addCC($cc);
            }
        $mail->addReplyTo($this->replyTo);//to, name            
        $mail->WordWrap = 50; 
        if(isset($attachement_path) && !empty($attachement_path)){                                
        // set word wrap to 50 characters
        $mail->AddAttachment($attachement_path);  // add attachments
                }
        $mail->isHTML(true);      // set email format to HTML           
        $mail->Subject = $subject;
        $mail->Body = $body;
        //$mail->AltBody = "This is the body in plain text for non-HTML mail clients";          
        if(!$mail->send()){
            $this->tempVar = $mail->ErrorInfo;
           return false;
            }
        else{
            return true;
            }
        }
      //for multiple recipients                
      public function sendEmails($to=array(),$from,$sender_name="",$subject,$body,$attachement_path="",$cc="",$bcc=""){
        require '../../../../vendor/autoload.php';              
        $mail = new PHPMailer;
        $mail->IsSMTP();            // set mailer to use SMTP i.e. 
        smtp1.example.com;smtp2.example.com
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->Host = $this->host;  // specify main and backup server
        $mail->SMTPAuth = true;     // turn on SMTP authentication
        $mail->Username = $this->userName;  // SMTP username i.e email id of an email address
        $mail->Password = $this->password; // SMTP password for the specified email address
        $mail->Port = 587;
        $mail->SMTPSecure = 'tls';
                    if($this->charSetOpt != 0){
                       $mail->CharSet = $this->charSet;
                    }
        $mail->From = $from;
        $mail->FromName = $sender_name;
        //$mail->addAddress($to[0]);   //mail,name
        foreach($to as $value){
            $mail->addAddress($value); 
            }
        if(isset($bcc) && !empty($bcc)){
            $mail->addBCC($bcc);
            }
        if(isset($cc) && !empty($cc)){
                $mail->addCC($cc);
            }
        //$mail->AddAddress("[email protected]");  // name is optional
        $mail->addReplyTo($this->replyTo);//to, name            
        $mail->WordWrap = 50; 
        if(isset($attachement_path) && !empty($attachement_path)){                                
        // set word wrap to 50 characters
                $mail->AddAttachment($attachement_path);         // add attachments
                //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    
        // optional name
                }
        $mail->isHTML(true);    // set email format to HTML         
        $mail->Subject = $subject;
        $mail->Body = $body;
        //$mail->AltBody = "This is the body in plain text for non-HTML mail clients";          
        if(!$mail->send()){
            $this->tempVar = $mail->ErrorInfo;
            return false;
            }
        else{
            return true;
            }
        }

       //for multiple/single recipient(s) and from random robots
       public function sendEmailRnd($to=array(),$sender_name="",$subject,$body,$attachement_path="",$cc="",$bcc=""){ 
        $this->get_email_user($this->robots);
        require '../../../../vendor/autoload.php';              
        $mail = new PHPMailer;
        $mail->IsSMTP();            // set mailer to use SMTP i.e. 
        smtp1.example.com;smtp2.example.com
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        //$mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->Host = $this->host;  // specify main and backup server
        $mail->SMTPAuth = true;     // turn on SMTP authentication
        $mail->Username = $this->userName;  // SMTP username i.e email id of an email address
        $mail->Password = $this->password; // SMTP password for the specified email address
        $mail->Port = 587;
        $mail->SMTPSecure = 'tls';
                    if($this->charSetOpt != 0){
                       $mail->CharSet = $this->charSet;
                    }
        $mail->From = $this->userName;
        $mail->FromName = $sender_name;
        //$mail->addAddress($to[0]);   //mail,name
        foreach($to as $value){
            $mail->addAddress($value); 
            }
        if(isset($bcc) && !empty($bcc)){
            $mail->addBCC($bcc);
            }
        if(isset($cc) && !empty($cc)){
                $mail->addCC($cc);
            }
        //$mail->AddAddress("[email protected]");                  // name is optional
        $mail->addReplyTo($this->replyTo);//to, name            
        $mail->WordWrap = 50; 
        if(isset($attachement_path) && !empty($attachement_path)){                                
        // set word wrap to 50 characters
                $mail->AddAttachment($attachement_path); // add attachments
        //$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
                }
        $mail->isHTML(true);  // set email format to HTML           
        $mail->Subject = $subject;
        $mail->Body = $body;
        //$mail->AltBody = "This is the body in plain text for non-HTML mail clients";          
        if(!$mail->send()){
            $this->tempVar = $mail->ErrorInfo;
            return false;
            }
        else{
            return true;
            $this->tempVar = $from;
            }
            $mail->smtpClose();
        }                       
    private function get_email_user($robots_array=array()){
        try{
            if(is_array($robots_array) && count($robots_array) > 0){
                //get random user id with password from the $robots array
                $sender_robot_ary = $this->robots[array_rand($this->robots,1)];
                $this->userName = $sender_robot_ary[0];
                $this->password = $sender_robot_ary[1];
            }
        }catch(Exception $exc){
            $this->tempVar = $exc;
            }
        }
 
}
Peptic answered 15/10, 2022 at 4:59 Comment(0)
R
1

Follow this simple step:

  • Login to your google account
  • Navigate to security -> Signing in to Google
  • Enable 2-factor authentication

You will see the "App passwords"

  • Click on this & Select Other(custom name)
  • name the device/application that you want to use
  • Click Generate

Then copy & paste the newly generated password that you are given into your code in place of the old password that you were using. i.e from your phpmailer script replace the formal password with the newly generated password.

$mail->Password = 'newly generated password';

Remontant answered 25/10, 2022 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.