How can authentication issues, such as "Could not authenticate," be resolved when using Gmail with PHPMailer?

Authentication issues like "Could not authenticate" in Gmail with PHPMailer can be resolved by ensuring that the correct SMTP settings are used, including the correct username and password. Additionally, enabling less secure app access in the Gmail account settings can help resolve this issue.

// PHP code snippet to resolve authentication issues in Gmail with PHPMailer

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@gmail.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('your@gmail.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body';

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