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?