gpt4 book ai didi

gmail-api - 带有 nodeJS 的 GMail API - 发送给出 400 错误请求

转载 作者:行者123 更新时间:2023-12-05 00:18:22 24 4
gpt4 key购买 nike

我正在为 nodeJS 使用最新的 (0.9.8) google-api-nodejs-client 库。
我正在使用服务帐户和范围为 https:\\googleapis.com/auth/gmail.send 的 JWT 进行身份验证。 (以及/auth/drive FWIW)。

我尝试像这样发送电子邮件(base64urlencoded):

req = mail.users.messages.send(
{
auth: jwtClient, // really works with google drive
userId: actual@gmail.com // actually a legit gmail address
resource: {
raw: message // base64encode(urlencode(RFC822 msg))
}
}, (err, res) => { console.log(err); }
);

并且回调接收到这个非常有用的对象:
{"code": 400,"errors":[{"domain":"global","reason":"failedPrecondition","message":"Bad Request"}]}

我知道 google-api-nodejs-client 是 alpha 并且 GMail API 本身正在发展(消息与资源等)。所以一些在线信息——包括谷歌自己的文档——是可以理解的不一致。我正在寻找任何建议,因为该错误似乎非常普遍。

最佳答案

好的。 “问题”是我自己造成的。解决方案分为三个(或四个)简单的部分。只是不要试图跳过任何。

tl;dr,但你仍然需要阅读!这是一个 working gist .

尽管您可能在别处读到过这些内容,但只要您有 Google Apps 帐户,就可以通过服务帐户使用 Gmail API。 (我就是这样做的。)这意味着您不必通过 OAuth 重定向来让您的服务器发送电子邮件。这是通过模拟实现的。 [注:如果您没有 Google Apps 域,您可能应该再次问自己为什么要在 Gmail 中使用服务帐户;毕竟,每封电子邮件都由发件人和收件人共同拥有,即使其中一个或两个都是机器人。]

以下是您需要做的:

  • 拥有 Google Apps 帐户。看上面。
  • 按照说明操作 here信。
  • 为您在上面第 2 步中配置的服务帐户启用对 Google Apps 域的 API 访问。第 2 步中的链接包含这些说明。但重要的是要重复。
  • 像这样生成你的 JWT:

  • var jwtClient = new google.auth.JWT(
    serviceaccount_key.client_email
    , null
    , serviceaccount_key.private_key
    , [
    'https://www.googleapis.com/auth/gmail.readonly'
    , 'https://www.googleapis.com/auth/gmail.send'
    ]
    , 'user@your_google_apps_domain' // a legit user
    )

    您需要的范围取决于您要进行哪些 API 调用并且已在您的 Google Apps 域中启用。

    我希望这可以为您节省半天时间。

    关于gmail-api - 带有 nodeJS 的 GMail API - 发送给出 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902022/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com