无法使用 Gmail 使用 PHPMailer 发送电子邮件(无法连接服务器)

Can't send email using PHPMailer using Gmail(Failed to connect server)

我正在尝试使用 PHPMailer 发送电子邮件。我看过一些关于使用这个包通过 Gmail 服务器发送电子邮件的主题,但我没有成功。

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP

$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587; // or 587

$mail->Username = "myEmailAddress@gmail.com";
$mail->Password = "MyGmailPassword";
$mail->setFrom('myEmailAddress@gmail.com', 'First Last');
$mail->addAddress('MyTargetEmail@example.com', 'John Doe');

$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->Body = 'Text to be sent';

if(!$mail->send()){
    echo 'message was not sent: ' . $mail->ErrorInfo;
}
else{
    echo 'Successfully sent';
}

我的回复:

2018-11-29 14:56:37 SMTP ERROR: Failed to connect to server:  (0)
<br>
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
<br>
message was not sent: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

您将电子邮件发送到错误的地方 port/configuration。在您的代码中,您已将其发送到处理 stmp 连接的端口 587,但您发送的是通过 ssl 配置的(需要通过端口 465 发送)。

需要将 ssl 的位置更改为 "tls",它将起作用。

$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587; // or 587

用 composer 试试这个

require phpmailer/phpmailer
    <?php
        use PHPMailer\PHPMailer\PHPMailer;
        require 'vendor/autoload.php';
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPDebug = 2;
        $mail->Host = 'smtp.gmail.com';
        $mail->Port = 587;
        $mail->SMTPAuth = true;enter code here
        $mail->Username = '@gmail.com';
        $mail->Password = '';
        $mail->setFrom('@gmail.com', '');
        $mail->addReplyTo('@gmail.com', '');
        $mail->addAddress('@gmail.com', ' Name');
        $mail->Subject = 'This for Testing PHPMailer';
        //$mail->msgHTML(file_get_contents('message.html'), __DIR__);
        $mail->Body = 'This is a plain text message body';
        //$mail->addAttachment('test.txt');
        if (!$mail->send()) {
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        } else {
            echo 'The email message was sent.';
        }
    ?>