SMTP ERROR: Failed to connect to server: Connection timed out (110) when using phpmailer

SMTP ERROR: Failed to connect to server: Connection timed out (110) when using phpmailer

这在我的旧服务器上运行得很好。

2020-07-18 16:37:45 SMTP 错误:无法连接到服务器:连接超时 (110) SMTP 连接 () 失败。 https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting 我现在使用的是 CentOS 7 和 php7.3.2

我试过的。

这是我的代码:

<?php
require_once "config.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $randompassword = generateRandomString();
    $email = $_POST['email'];
    $mail = new PHPMailer(true);
    try {
        $connect->query("SET NAMES 'utf8'");
        $insertSql = "INSERT INTO users (username, password, email, forgot) VALUES ('$name', '$randompassword', '$email', 1)";
        $status = $connect->query($insertSql);
        $mail->isSMTP();                                            // Send using SMTP
        $mail->SMTPAuth   = true;
        $mail->Host       = 'smtp.gmail.com';                    // Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
        $mail->Username   = 'username@gmail.com';                     // SMTP username
        $mail->Password   = '*******';                               // SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
        $mail->Charset    = "UTF-8";
        $mail->setFrom('username@gmail.com', 'Mailer');
        $mail->addAddress($email);               // Name is optional
        $mail->addReplyTo('to@gmail.com', 'to');                                 // Set email format to HTML
        $mail->Subject = 'subject';
        $mail->Body    = 'body'
        $mail->send();
        echo '<script>alert("already send");</script>'; 
    } 
    catch (Exception $e) {
        echo "<script>alert('error');</script>";
        echo !extension_loaded('openssl')?"Not Available":"Available";
        exit;
    }
}
?>

更新

我测试 telnet smtp.gmail.com 端口 25 465 587,结果也是连接时间 out.Then 我在我的电脑上测试得到正常结果。

网络问题。防火墙正在阻止这些端口。令人惊讶的是它也阻止了 SSL 端口。一旦你解决了这个问题,你就可以开始了。或者,您可以将 SMTP 服务器上的端口更改为提供商允许您使用的自定义端口(25000、25252 等)。

我使用的是 Linode 服务器,他们封锁了端口 25、465、587,所以我无法发送邮件和远程登录 smtp.gmail.com。 for more infomation, ckick here.