【问题标题】:Failed sending mail with googleapis' service account and JWT auth in nodejs使用 googleapis 的服务帐户和 nodejs 中的 JWT auth 发送邮件失败
【发布时间】:2015-01-13 03:41:29
【问题描述】:

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

此代码 sn-p 来自以下 StackOverflow 链接:Failed sending mail through google api in nodejs

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

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

我错过了什么?

【问题讨论】:

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


【解决方案1】:

根据 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 nodejsauth: OAuth2Client 中看到的,他们正在使用 OAuth2 客户端进行身份验证。目前,您无法使用 GMail API 发送消息,除非以特定 GMail 用户身份进行身份验证。服务帐号无法像普通用户那样访问 GMail。

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

【讨论】:

  • 所以你是说即使我拥有该特定域的所有管理员权限,如果没有他们的交互(直接由用户手动验证),也无法获取用户电子邮件?
猜你喜欢
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2021-03-15
  • 2016-09-11
  • 2019-11-19
  • 2020-09-30
相关资源
最近更新 更多