繁体   English   中英

Swiftmailer无法使用oauth2令牌向GMail进行身份验证

[英]Swiftmailer unable to authenticate to GMail using oauth2 token

我正在尝试使用SwiftMailer登录到我具有有效访问令牌的GMail帐户。 我可以使用帐户凭据成功登录:

$Transport = new Swift_SmtpTransport('smtp.gmail.com',587,'tls');
$Transport->setAuthMode('login')
          ->setUsername('my-email-address')
          ->setPassword('my-password');

$Mailer = new Swift_Mailer($Transport);
// ... make a new message & send it

但是,如果我将代码更改为使用我的oauth2令牌,如下所示:

$access_token = 'ya29.GLv....'; 
$Transport = new Swift_SmtpTransport('smtp.gmail.com',587,'tls');
$Transport->setAuthMode('XOAUTH2')
          ->setUsername('my-email-address')
          ->setPassword($access_token);

$Mailer = new Swift_Mailer($Transport);

我收到错误消息: Swift_TransportException: Expected response code 250 but got code "535".... Username and Password are not accepted.

我在其他地方使用GMail API使用了相同的访问令牌,因此我知道该令牌有效。

我想念什么?

编辑

只需在调试器打开的情况下再次运行代码。 似乎第一个错误代码是334,并显示以下消息:

Expected response code 235 but got code "334", with message "334 eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==

该消息的编码部分解码为:

{"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}

您可能会遇到的最大障碍,没有人在谈论,这是权限不足 SwiftMailer在阐述此问题方面做得不好。 因此,在与SwiftMailer一起使用之前,您可能希望使用GoogleClient来确保您的凭据有效。

完整的源代码

# Using SwiftMailer

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
    ->setAuthMode('XOAUTH2')
    ->setUsername('<SENDER_EMAIL>')
    ->setPassword('<ACCESS_TOKEN>');

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message())
    ->setFrom(['<SENDER_EMAIL>' => '<SENDER_NAME>'])
    ->setTo(explode(';', '<RECEIVER_EMAIL>'))
    ->setSubject('<SUBJECT')
    ->setBody('<MESSGAE_BODY>');

// Send the message
if ($mailer->send($message)) {
    print 'Mail sent...';
    exit();
}

echo('Mail not sent...');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM