PHPMailer Google Oauth2身份验证问题

时间:2019-06-14 12:07:57

标签: php symfony phpmailer gmail-api google-oauth2

我的目标是通过gmail API从经过身份验证的用户的gmail帐户发送电子邮件。为此,我正在使用PHPMailer。 问题是我在尝试发送电子邮件之前遇到SMTP Error: Could not authenticate.错误。

这是到目前为止我使用 Google API PHP客户端的目的:

  1. 在Google控制台上设置网络应用,并获得客户端秘密令牌
  2. 通过自己的Google凭据成功登录用户,并 将访问令牌交换为授权代码。也得到了 刷新令牌。
  3. 我已安装的库为:
    • “ google / apiclient”:“ ^ 2.0”,
    • “ phpmailer / phpmailer”:“〜6.0”,
    • “ league / oauth2-client”:“ ^ 2.0”,
    • “ league / oauth2-google”:“ ^ 3.0”,
    • “ paragonie / random_compat”:“ ^ 1 | ^ 2 | ^ 9.99”

这是我的代码:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
use League\OAuth2\Client\Provider\Google;

.
.
.
.

$mail = new PHPMailer(true);

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

$email = 'mygoogleconsolemailaddress@gmail.com;
$clientId = 'randomcharactershere346346346.apps.googleusercontent.com';
$clientSecret = 'thatsmysecretactually------';

$mail->Body = $this->renderView('MailingBundle:Mail:email_account_verification.html.twig',
    array(
        'senderName' => 'userwantingtosendmail@gmail.com'
    )
);

$provider = new Google(
    [
        'clientId' => $clientId,
        'clientSecret' => $clientSecret
    ]
);

$mail->setOAuth(
    new OAuth(
        [
            'provider' => $provider,
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
            'refreshToken' => $refreshToken,    //i get that from another method and yes i can successfully get it
            'userName' => $email,
        ]
    )
);

$mail->setFrom('senderemail@gmail.com', 'Some name here');
$mail->addAddress('tohere@gmail.com', 'Some name here');
$mail->Subject = "Subject here"
$mail->CharSet = 'utf-8';

$mail->send();

我已阅读以下文档,但无法解决我的问题: https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2 https://github.com/PHPMailer/PHPMailer/blob/v6.0.1/examples/gmail_xoauth.phps

谢谢。

0 个答案:

没有答案