I’m using PHP Mailer for Mail send process. when i use that i have recieving one error message which is
Error:
Admin: Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host. Failed to connect to serverSMTP server error: Failed to connect to server
all data recieving into database when comming to this part: if ($conn) { $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $email); if (!$stmt->execute()) { echo "Error: Unable to insert data into the database."; exit(); } $stmt->close(); } else { echo "Error: Unable to connect to the database."; exit(); }
But the problem is occuring when send the email for Admin. Give me a solution and let me know what is happening there, and i have set correct all the credentials.
My full code
require '../phpmailer/src/Exception.php';
require '../phpmailer/src/PHPMailer.php';
require '../phpmailer/src/SMTP.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['username']) && !empty($_POST['email'])) {
$name = $_POST['username'];
$mail = $_POST['email'];
// Save data to the database
$conn = Connection();
if ($conn) {
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
if (!$stmt->execute()) {
echo "Error: Unable to insert data into the database.";
exit();
}
$stmt->close();
} else {
echo "Error: Unable to connect to the database.";
exit();
}
// Send email to admin
try {
$mailAdmin = new PHPMailer(true);
$mailAdmin->isSMTP();
$mailAdmin->Host = 'smtp.gmail.com';
$mailAdmin->SMTPAuth = true;
$mailAdmin->Username = '[email protected]';
$mailAdmin->Password = 'my authentication key';
$mailAdmin->SMTPSecure = 'ssl';
$mailAdmin->Port = 465;
$mailAdmin->setFrom('[email protected]', 'HIII');
$mailAdmin->addAddress('[email protected]');
$mailAdmin->addReplyTo($email, $name);
$mailAdmin->isHTML(true);
$mailAdmin->Subject = "New One Arrived";
$mailAdmin->Body = "A new form submission has been received.<br><br>
Name: $name<br>Email: $email<br>";
$mailAdmin->send();
} catch (Exception $e) {
echo 'Admin: Message could not be sent. Mailer Error: ', $mailAdmin->ErrorInfo;
exit();
}
// Send thank you email to user
try {
$mailUser = new PHPMailer(true);
$mailUser->isSMTP();
$mailUser->Host = 'smtp.gmail.com';
$mailUser->SMTPAuth = true;
$mailUser->Username = '[email protected]';
$mailUser->Password = 'my authentication key';
$mailUser->SMTPSecure = 'ssl';
$mailUser->Port = 465;
$mailUser->setFrom('[email protected]', 'HIII');
$mailUser->addAddress($email);
$mailUser->isHTML(true);
$mailUser->Subject = "Thank You for Your Enquiry";
$mailUser->Body = "Dear $name,<br><br>";
$mailUser->send();
} catch (Exception $e) {
echo 'User: Message could not be sent. Mailer Error: ', $mailUser->ErrorInfo;
exit();
}
// Redirect to dashboard only if both emails are sent successfully
//if ($adminEmailSent && $userEmailSent) {
header('Location: dashboard.php');
exit();
} else {
echo 'An error occurred while processing your request.';
}
}
2
Answers
Maybe your server cannot connect to smtp.gmail.com on port 465
You can change to port 587 with
$mailAdmin->SMTPSecure = 'tls';
If it still doesn’t work, I think your server or country doesn’t allow connecting to google servers …
First off, Welcome to Stack Overflow! Let’s talk about some PHP principles before I post code that works in my env 🙂
I see you are importing files manually, explicitly typing out
import
. I’m on the internals mailing list where we discuss changes that are request to be made (php is written in C), and this topic has been bouncing around this month: there is an RFC that was published this morning forstatic class
, which at the time of writing is not a part of PHP, but I do believe it will pass the vote. Why though? It is extremely common to have a function that does not need the context or concepts of object-oriented programming. Still, in PHP, a design decision was made that functions declared in a file not wrapped innamespace XYZ{}
or begins with anamespace XYZ;
should be in the global scope. This makes dynamically loading PHP files only when needed impossible for un-namespaced functions. If every file in your application is loaded into memory for every request, then it will be very slow. So static classes are coming strictly because ofautoloading principles
.The community also follows PHP-FIG; don’t let anyone tell you differently. Specifically, PSR-4 talks about autoloading and how to
namespace
your files.But let’s not re-invent the wheel, no, PHP users also use
composer
. It’s likenpm
,pip
,dnf
,apt
,brew
,choco
, etc. It lets the PHP community use open source code super quickly… You probably manually downloaded thePHP-Mailer
but really you should have defined it in yourcomposer.json
file. The example above uses version:Shameless plug my ThrowableHandler.php that will handle anything that can be caught in PHP.