Skip to main content

cofigure app password for gmail smtp usage in php

To use Gmail SMTP with PHP, you must enable 2-Step Verification in your Google Account, generate a 16-character

App Password from the Security settings, and then use that App Password in your PHP (e.g., PHPMailer) code instead of your regular Gmail password for SMTP authentication. You'll use smtp.gmail.com, port 587 with TLS/STARTTLS, and your full Gmail address as the username in your script. 



Part 1: Generate the App Password (Google Account)

  1. Enable 2-Step Verification: Go to your Google Account settings, find the "Security" tab, and ensure 2-Step Verification is turned ON.
  2. Go to App Passwords: Navigate to the App Passwords page (you may need to sign in again).
  3. Select App/Device: In the dropdowns, select "Mail" for the app and "Other (Custom name)" for the device (e.g., "My PHP App"), then click "Generate".
  4. Copy Password: Google will provide a 16-character password. Copy this immediately, as you won't see it again. 

Part 2: Configure Your PHP Script (PHPMailer Example)

Use the generated 16-character password in your SMTP settings. 


php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // If using Composer

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();                            // Send using SMTP
    $mail->Host       = 'smtp.gmail.com';       // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                   // Enable SMTP authentication
    $mail->Username   = 'your_email@gmail.com'; // Your Gmail address
    // Use the 16-character App Password here, NOT your regular password
    $mail->Password   = 'your_16_char_app_password'; // <<< PASTE THE GENERATED PASSWORD
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption
    $mail->Port       = 587;                    // TCP port to connect to

    // Recipients
    $mail->setFrom('your_email@gmail.com', 'Your Name');
    $mail->addAddress('recipient_email@example.com'); // Add a recipient

    // Content
    $mail->isHTML(true);                        // Set email format to HTML
    $mail->Subject = 'Test Email from PHP';
    $mail->Body    = 'This is a test email sent using Gmail SMTP with an App Password.';

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

Key SMTP Settings for Gmail

  • Host: smtp.gmail.com
  • Port: 587
  • Encryption: TLS (STARTTLS)
  • Username: Your full Gmail address
  • Password: Your 16-character App Password