GMail API 与 nodeJS - 发送给出 400 错误请求

GMail API with nodeJS - send gives 400 Bad Request

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

我尝试像这样发送电子邮件(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 本身正在发展(消息与资源等)。所以一些在线信息——包括 Google 自己的文档——是不一致的,这是可以理解的。我正在寻找任何建议,因为错误似乎很普遍。

好的。 "problem" 是我自己制作的。解决方案分为三个(或四个)简单的部分。只是不要试图跳过任何一个。

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

尽管您可能在其他地方读到过内容,但 可以通过服务帐户使用 Gmail API -- 前提是您有 Google 应用程序帐户。 (我这样做了。)这意味着您不必为了让您的服务器发送电子邮件而乱用 OAuth 重定向。这是通过模仿来完成的。 [N.B。如果您没有 Google Apps 域,您可能应该再问问自己为什么要在 Gmail 中使用服务帐户;毕竟,每封电子邮件都由发件人和收件人共同拥有,即使其中一个或两个都是机器人。]

这是您需要做的:

  1. 有一个 Google Apps 帐户。见上文。
  2. 按照说明 here 来信。
  3. 为您在上面第 2 步中配置的服务帐户启用 API 访问您的 Google Apps 域。第 2 步中的 link 包含这些说明。但重要的是要重复。
  4. 像这样生成你的 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 应用程序域中启用。

希望这能为您节省半天时间。