【问题标题】:Nodemailer Oauth2 error : unauthorized_clientNodemailer Oauth2 错误:未授权客户端
【发布时间】:2020-03-27 04:49:39
【问题描述】:

我正在尝试在 nodejs 应用程序上使用 Oauth 和 nodemailer 发送邮件,我没有使用 Oauth,但我的密码写在代码中,所以我将自己转向 Oauth。

我只想连接自己以自动发送邮件。 我已经在谷歌云平台上设置了一个项目和一个服务帐户。我添加了 gmail api 并编写了一些代码:

 var smtpTransport = nodemailer.createTransport({
   host:'smtp.gmail.com',
   port:465,
   secure:true,
   auth:{
     type: 'OAuth2',
     user: 'thomas.legrand.test@gmail.com',
     serviceClient:config.client_id,
     privateKey:config.private_key
   }
 });
 var mail = {
   from: "thomas.legrand.test@gmail.com",
   to: "thomas.legrand26@gmail.com",
   subject:"Un sujet abstrait",
   html:"<h1> Ceci est un mail de test </h1><h2> et ceci un sous titre </h2> "
 };

 smtpTransport.on('token', token => {
    console.log('A new access token was generated');
    console.log('User: %s', token.user);
    console.log('Access Token: %s', token.accessToken);
    console.log('Expires: %s', new Date(token.expires));
});

smtpTransport.sendMail(mail, function(error, response) {
        if(error) {
          console.log("Erreur lors de l'envoie du mail ");
          console.log(error);
        }else {
          console.log("succes")
        }
        smtpTransport.close();
      });

但我得到了一个我无法解决的error (unauthorized_client)。

我希望你能帮助我或至少给我一些提示!

【问题讨论】:

    标签: node.js email oauth gmail-api nodemailer


    【解决方案1】:

    一切看起来都很好,但请确保以下几点:

    1. Gmail SMTP 的正确 OAuth2 范围是 https://mail.google.com/,请确保您的客户端在为用户请求权限时设置了此范围。

    2. 确保为您的客户端 ID 启用了 Gmail API 访问。为此,请在 Google API Manager 中搜索 Gmail API,然后点击“启用”

    另外,请确保正确传递 clientId 和私钥。

    【讨论】:

      【解决方案2】:

      验证您是否遵循这些步骤,以确保您以正确的方式设置您的客户:

      然后不要忘记启用您的 Gmail API,就像这里所说的那样:

      另外,我建议您查看Gmail API Quickstart

      【讨论】:

      • 我觉得我走的很好!我做了你放的最后一个链接,现在我得到了一个新错误:invalid_grant,我会自己搜索。谢谢
      • 不客气!如果对您有帮助,请考虑将我的答案标记为最佳答案
      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 2019-07-13
      • 2016-06-29
      • 2013-08-03
      • 2018-10-20
      • 1970-01-01
      • 2017-02-22
      • 2016-06-02
      相关资源
      最近更新 更多