xampp + PHPMailer + Gmail = SMTP错误:无法连接到SMTP主机

时间:2017-10-20 21:20:31

标签: php smtp phpmailer

我已经使用Composer安装了PHPMailer并添加了所有Composer依赖项以使用Google XOAuth2身份验证。 然后我按照一些教程使用Gmail API获取刷新令牌 一切都应该工作得很好。我做了所有的文书工作。对不对?

尽管我有最好的意图和所有文档,但我无法与smtp.gmail.com建立SMTP连接 我收到这个错误:

2017-10-20 18:01:45 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP c17sm2715728wrg.26 - gsmtp
2017-10-20 18:01:45 CLIENT -> SERVER: EHLO localhost
2017-10-20 18:01:45 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [151.61.40.58]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2017-10-20 18:01:45 CLIENT -> SERVER: STARTTLS
2017-10-20 18:01:45 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
SMTP Error: Could not connect to SMTP host.
2017-10-20 18:01:45 CLIENT -> SERVER: QUIT
2017-10-20 18:01:45
2017-10-20 18:01:45
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


我的代码直接来自PHPMailer Gmail XOAUTH示例。

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\OAuth;

use League\OAuth2\Client\Provider\Google;

date_default_timezone_set('Europe/Rome');

require 'lib/php/vendor/autoload.php';

$mail = new PHPMailer;

$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';

$email = 'seckrit-stuff';
$clientId = 'seckrit-stuff';
$clientSecret = 'seckrit-stuff';
$refreshToken = 'seckrit-stuff';

$provider = new Google(
    [
        'clientId' => $clientId,
        'clientSecret' => $clientSecret,
    ]
);
$mail->setOAuth(
    new OAuth(
        [
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,
            'userName' => $email,
        ]
    )
);

$mail->setFrom($email, 'Matteo Bini');
$mail->addAddress('seckrit-stuff', 'Matteo Bini');
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
$mail->CharSet = 'utf-8';
$mail->msgHTML('<strong>HTML</strong> message!');
$mail->AltBody = 'This is a plain-text message body';


if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}


你能帮我找一个在localhost(xampp)中使用PHPMailer和Gmail的方法吗?

1 个答案:

答案 0 :(得分:2)

这与OAuth无关。你在TLS级别有一个更早的问题。你错过了openssl扩展,它配置错误,或者你的CA证书都已过时。

错误链接到的故障排除指南中介绍了此问题 - 请使用openssl进行检查。