I’m encountering an issue while trying to send emails using PHP’s PHPMailer library. I’m getting an error that says ‘Cannot Send Mail.’ and I’ve tried different ways to send mail even I got helped from ChatGpt but I could not. I’ve followed the documentation and my code looks like this:
<form action="mail.php" method="post">
<input type="text" name="name">
<input type="email" name="email" id="">
<input type="submit" value="submit">
</form>
<?php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
require __DIR__ . '/PHPMailer-master/PHPMailer.php';
require __DIR__ . '/PHPMailer-master/Exception.php';
require __DIR__ . '/PHPMailer-master/SMTP.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$mail = new PHPMailer(true);
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'mypassword'; // Replace with your Gmail password
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Sender and recipient details
$mail->setFrom('[email protected]', 'Ahmed Maajid');
$mail->addAddress('[email protected]'); // Set your Gmail address as both sender and recipient
// Email content
$mail->isHTML(false);
$mail->Subject = 'New submission from your website';
$mail->Body = 'Name: ' . $name . "nn" . 'Email: ' . $email;
$mail->send();
echo 'Email sent successfully!';
} catch (Exception $e) {
echo 'Oops! There was a problem: ' . $mail->ErrorInfo;
}
}
?>
2
Answers
Composer is the easiest way to get PHPMailer up and running. Just open your terminal and type:
composer require phpmailer/phpmailer
. Here’s the code snippet to send an email:You may recheck the following
Your gmail password isn’t actually the password you use to sign in to your gmail account. If you’re using Google’s SMTP, it should be the password generated duration App password creating.
If you’re using localhost, you still need to be connected to the internet (if you’re using SMTP)
I hope you’ve modified the … example fields with your own configuration.
You may refer to the web for how set up Google SMTP for PHPMailer
Bonus Temporary enable the debug true so you can know more about the error
Thanks!