IT Technical Support for Developers

Windows

Share

PHPMailer Enable 2FA Send Mail with 2 Step Authentication

How to send mail using PHP mailer if two factor authentication?

2 Step Verification

Gmail 2 steps verification

To send emails using PHPMailer with 2-factor authentication (2FA), you'll need to generate an "App Password" or set up OAuth2. Instead of your regular password, use the App Password in PHPMailer's settings.

Steps to Create App Password

Enable 2FA: Make sure 2FA is enabled in your Google Account.

Create a custom app in your Gmail security settings.
Step 1 Click Google Apps icon (right side top near user logo)
Step 2 Click Account
Step 3 Click Security Menu from left side
Step 4 Type "App password" in the search field
Step 5 Click "App Password" Link
Step 6 Enter the App Name as PHPMailer and submit
Step 7 You will get App Password.(It will generate a token to use in the App )

This is what you'll use in PHPMailer.

Sample Code

$email = new PHPMailer(true);

$email->IsSMTP(); // Use SMTP
$email->Host= 'smtp.gmail.com'; // Sets SMTP server

$email->SMTPDebug = 0; // 2 to enable SMTP debug information
$email->Debugoutput = 'html';
$email->SMTPAuth = TRUE; // enable SMTP authentication
$email->SMTPSecure = "SSL"; //Secure conection
$email->Port = 587; // set the SMTP port
$email->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);

$email->Username = 'your_email@gmail.com'; // Your Gmail address
$email->Password = 'your_app_password'; // The App Password
$email->setFrom('your_email@gmail.com', 'Your Name');
$email->addAddress('recipient@example.com', 'Recipient Name');
$email->Subject = '2FA Test Email';
$email->Body = 'This is 2 Step Verification Mail Sent by PHPMailer.';

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

Use the token as password in combination with your full Gmail account and two factor authentication will not be required.

How to enable two factor authentication in Gmail

Hits: 377, Rating : ( 5 ) by 1 User(s).