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

时间:2018-11-29 15:09:54

标签: php composer-php phpmailer

我正在尝试使用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

2 个答案:

答案 0 :(得分:1)

您正在将电子邮件发送到错误的端口/配置。在您的代码中,已将其发送到处理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

答案 1 :(得分:0)

尝试使用作曲家

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.';
        }
    ?>