【问题标题】:Swiftmailer unable to authenticate to GMail using oauth2 tokenSwiftmailer 无法使用 oauth2 令牌对 GMail 进行身份验证
【发布时间】:2018-11-14 07:06:10
【问题描述】:

我正在尝试使用 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 的愿望是我可以使用它为电子邮件生成 mime。我仍然可以使用 Swift_Message 和 Swift_Message->toString() 来做到这一点,然后只需使用 Service->users_messages->send() 来实际发送消息。仍然通过笨拙的 Google 库进行连接。
  • 经过多次尝试,我设法让它工作。问题是我没有足够的权限。所以 swiftmailer 会失败而没有详细的消息……我使用默认的 GoogleClient 来诊断问题,然后 swiftmailer 就可以正常工作了。让我为可能遇到相同问题的人留下答案

标签: php smtp gmail swiftmailer smtp-auth


【解决方案1】:

您可能面临的最大障碍是权限不足。 SwiftMailer 没有很好地阐述这个问题。因此,在将它们与 SwiftMailer 一起使用之前,您可能需要使用 GoogleClient 来确保您的凭据正常工作。

Full source code

# 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...');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2020-06-24
    • 1970-01-01
    • 2018-01-08
    • 2021-05-12
    相关资源
    最近更新 更多