I have a problem with my code, I am trying to send an email using PHPMailer but it gives me the following error: SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP Error: Could not connect to SMTP host. Failed to connect to server
.
My code is like this:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require '../lib/PHPMailer/Exception.php';
require '../lib/PHPMailer/PHPMailer.php';
require '../lib/PHPMailer/SMTP.php';
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = '*******';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom('[email protected]');
$mail->addAddress('[email protected]');
$mail->isHTML(true);
$mail->Subject = 'Application';
$mail->Body ='<h1>Application</h1>';
$mail->send();
$exito = 1;
} catch (Exception $e) {
$exito = 0;
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
It works perfectly in localhost configured in this way, but when I upload it to my host (cpanel), it throws the error and fails, I'm already checking if the ip is blocked, changing ports and encryption but it throws the same error.
Will someone have a configuration present that I am missing or a recommendation?
You should validate that the ports are open at your host and eliminate at least one of the possible issues.
Here's a simple script that attempts to connect through various ports, and returns a SUCCESS or ERROR message for each.
<?php
$servers = array(
array("smtp.gmail.com", 465),
array("smtp.gmail.com", 587),
);
foreach ($servers as $server) {
list($server, $port) = $server;
echo "<h1>Attempting connect to <tt>$server:$port</tt></h1>\n";
flush();
$socket = fsockopen($server, $port, $errno, $errstr, 10);
if(!$socket) {
echo "<p>ERROR: $server:$portsmtp - $errstr ($errno)</p>\n";
} else {
echo "<p>SUCCESS: $server:$port - ok</p>\n";
}
flush();
}