PHPMailer Gmail SMTP configuration issues

Need help with PHPMailer and Gmail setup

I’m working on a contact form for my website and trying to set up email sending through Gmail using PHPMailer. I built the HTML form already but I’m running into problems when trying to send emails.

Here’s what I have so far:

<?php
$fullname = $_POST['fullname'] ?? '';
$user_email = $_POST['user_email'] ?? '';
$subject_line = $_POST['subject_line'] ?? '';
$user_message = $_POST['user_message'] ?? '';

if(isset($_POST['submit_form'])){
    require_once '../phpmailer/PHPMailer.php';
    
    $mailer = new PHPMailer(true);
    $mailer->isSMTP();
    $mailer->SMTPDebug = 2;
    $mailer->SMTPAuth = true;
    $mailer->SMTPSecure = 'tls';
    $mailer->Host = 'smtp.gmail.com';
    $mailer->Port = 587;
    $mailer->Username = '[email protected]';
    $mailer->Password = 'app_password';
    
    $mailer->setFrom('[email protected]', 'Contact Form');
    $mailer->addAddress('[email protected]');
    $mailer->isHTML(true);
    $mailer->Subject = $subject_line;
    $mailer->Body = '<p>' . $user_message . '</p>';
    
    try {
        $mailer->send();
        echo 'Email sent successfully';
    } catch (Exception $e) {
        echo 'Error occurred: ' . $mailer->ErrorInfo;
    }
}
?>

I keep getting authentication errors and the emails won’t send. What am I doing wrong with the Gmail configuration?

Check your namespace for PHPMailer - you’re probably missing the ‘use’ statements at the top. Try port 465 with SSL instead of TLS/587. Gmail can be picky about that. I had the same auth errors because I wasn’t importing the files right. Should be use PHPMailer\PHPMailer\PHPMailer; depending on your version.

Turn off SMTPDebug in production - set it to 0 instead of 2. Debug mode messes with email sending and can leak sensitive info. Also check that your Gmail allows SMTP access for third-party apps. I had the same auth issues until I found out Gmail automatically disabled SMTP after flagging unusual activity. Go to your Google Account security settings and look for blocked sign-in attempts. Google blocks connections even with correct app passwords if the request comes from an unfamiliar server. Your PHPMailer setup looks fine otherwise.

Had the exact same problem when I first set up PHPMailer with Gmail. It’s almost always the app password or 2FA setup that’s screwing things up. Make sure you’ve got two-factor auth turned on in Gmail first, then create a specific app password for PHPMailer - don’t use your regular Gmail password. Check that you’re copying the app password correctly without any spaces or dashes. Gmail’s security settings also tripped me up - you might need to allow less secure apps or whitelist your server’s IP in Google’s security console. Your code looks good, so it’s definitely a Gmail credentials or security issue.