Nodemailer Oauth2错误:authorized_client

时间:2019-12-02 14:41:03

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

我正在尝试在nodejs应用上使用Oauth和nodemailer发送邮件,我在没有Oauth的情况下进行了邮件发送,但是我的密码写在了代码中,所以我将自己转为Oauth。

我只想连接自己以自动方式发送邮件。 我已经在Google Cloud Platform上建立了一个项目和一个服务帐户。我添加了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(未经授权的客户端),我无法解决。

希望您能帮助我或至少给我提示!

2 个答案:

答案 0 :(得分:1)

一切正常,但请确保以下内容:

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

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

还要确保正确传递了clientId和私钥。

答案 1 :(得分:0)

请确认您已按照以下步骤操作,以确保您以正确的方式设置了客户:

然后别忘了启用Gmail API,如此处所述:

此外,我建议您检查Gmail API Quickstart