node.js - Nodemailer Oauth2 错误 : unauthorized_client

标签 node.js email oauth gmail-api nodemailer

我正在尝试在 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) 我无法解决。

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

最佳答案

验证您是否按照以下步骤操作,以确保您以正确的方式设置您的客户端:

  • Setting up API keys .

  • 然后不要忘记启用您的 Gmail API,就像这里所说的:
  • Enable and disable APIs .

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

    关于node.js - Nodemailer Oauth2 错误 : unauthorized_client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59141210/

    相关文章:

    node.js - 如何根据常见的数组元素对文档进行匹配和排序

    电子邮件:具有互斥值的合法重复电子邮件标题键

    python - 使用 python 的 oauth 谷歌

    git - 将文件提交到 github,然后取消暂存,因为它包含敏感数据

    iphone - 使用 Oauth 从 iPhone 应用程序发送推文

    javascript - Azure 部署错误 errno 47

    javascript - 使用正则表达式提取电子邮件字段

    python - “coroutine”对象没有属性 get || pyppeteer

    java - 获取 javax.mail.MessagingException

    email - 发送邮件到 mailtrap.io