带有nodeJS的GMail API - send给出400 Bad Request

Car*_*los 4 gmail-api

我正在使用nodeJS的最新(0.9.8)google-api-nodejs-client库.我正在使用服务帐户和JWT作用域进行https:\\googleapis.com/auth/gmail.send身份验证(以及/ 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); }
);
Run Code Online (Sandbox Code Playgroud)

并且回调接收到这个非常有用的对象:

{"code": 400,"errors":[{"domain":"global","reason":"failedPrecondition","message":"Bad Request"}]}
Run Code Online (Sandbox Code Playgroud)

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

Car*_*los 6

好."问题"是我自己造成的.解决方案有三个(或四个)简单部件.只是不要试图跳过任何.

tl;博士,但你仍然需要阅读!这是一个有用的要点.

尽管你可能在其他地方看,它可以使用Gmail API与服务帐户-只要你有一个谷歌Apps帐户.(我这样做.)这意味着您不必乱用OAuth重定向来让您的服务器发送电子邮件.这是通过模仿来实现的.[NB如果您没有Google Apps域名,您可能应该再次问自己为什么要在Gmail中使用服务帐户; 毕竟,即使一个或两个都是机器人,每封电子邮件都由发件人和收件人共同拥有.

这是你需要做的:

  1. 拥有Google Apps帐户.往上看.
  2. 按照这里的说明写信.
  3. 为您在上面步骤2中配置的服务帐户启用对Google Apps域的API访问.步骤2中的链接包含这些说明.但重要的是重要.
  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
)
Run Code Online (Sandbox Code Playgroud)

您需要的范围取决于您要在Google Apps域中启用启用的API调用.

我希望这能为你节省半天时间.