javascript - 在 nodejs 中使用 googleapis 的服务帐户和 JWT 身份验证发送邮件失败

标签 javascript node.js google-api gmail google-apis-explorer

我正在尝试使用服务帐户和 JWT 身份验证发送电子邮件,但不断收到错误消息并显示一条非常无用的消息:{ code: 500, message: null }

此代码片段来自以下 StackOverflow 链接:Failed sending mail through google api in nodejs

似乎解决方案是将参数中的键更改为 resource 而不是 message 但它对我不起作用。这很奇怪,因为在文档 ( https://developers.google.com/gmail/api/v1/reference/users/messages/send ) 的 JS 示例中,它声称 key 仍然是 message

我正在验证

var jwtClient = new google.auth.JWT(config.SERVICE_EMAIL, config.SERVICE_KEY_PATH, null, config.ALLOWED_SCOPES);

然后发送一封电子邮件

jwtClient.authorize(function(err, res) {
  if (err) return console.log('err', err);

  var email_lines = [];

  email_lines.push("From: \"Some Name Here\" <rootyadaim@gmail.com>");
  email_lines.push("To: hanochg@gmail.com");
  email_lines.push('Content-type: text/html;charset=iso-8859-1');
  email_lines.push('MIME-Version: 1.0');
  email_lines.push("Subject: New future subject here");
  email_lines.push("");
  email_lines.push("And the body text goes here");
  email_lines.push("<b>And the bold text goes here</b>");

  var email = email_lines.join("\r\n").trim();

  var base64EncodedEmailSafe = new Buffer(email).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');

  var params = {
    auth: jwtClient,
    userId: "myaddress@gmail.com",
    resource: {
      raw: base64EncodedEmailSafe
    }
  };

  gmail.users.messages.send(params, function(err, res) {
    if (err) console.log('error sending mail', err);
    else console.log('great success', res);
  });
}

库中的评论似乎说资源也是正确的属性(https://github.com/google/google-api-nodejs-client/blob/master/apis/gmail/v1.js)

The comments in the library seem to say that resource is the correct property as well 我错过了什么?

最佳答案

根据 github 上的@ryanseys

您不能使用 JWT 授权 Gmail API 请求,您必须使用 OAuth 2.0,因为它需要授权给特定用户。否则您将能够做一些非常阴暗的事情,例如冒充他人发送消息。 Google APIs Explorer 使用 OAuth 2.0 进行身份验证,这就是它工作的原因。参见 https://developers.google.com/gmail/api/auth/about-auth获取更多信息。

正如您在 Failed sending mail through google api in nodejs 中看到的那样, auth: OAuth2Client,他们正在使用 OAuth2 客户端进行身份验证。当前,您无法在不作为特定 GMail 用户进行身份验证的情况下使用 GMail API 发送邮件。服务帐户无法像普通用户那样访问 GMail。

希望这可以帮助其他尝试使用服务帐户发送邮件的人!

关于javascript - 在 nodejs 中使用 googleapis 的服务帐户和 JWT 身份验证发送邮件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27914545/

相关文章:

javascript - jquery ui 拖放功能在移动设备上不起作用

javascript - 如何使用 Morgan 在请求和响应之间正确拆分日志记录?

google-api - 如何区分Google股票API中具有相同名称的股票代码

java - notifyDataSetChanged();未找到源异常

javascript - Android 工作室 - 调试 Javascript

javascript - 如何在Node.js中解释和执行异步javascript?

javascript - 使用同构网络应用程序的目的是什么?

javascript - Node.js 视频的完整路径

javascript - 谷歌登录点击两次?

javascript - 解析 Node.js 模块中的 JavaScript 代码