4

I'am trying to send mail using Oauth and nodemailer on a nodejs app, I did it without Oauth but my password was wrote in the code so I turn myself to Oauth.

I only want to connect myself to send mail in an automatic way. I have settup a project and a service account on google cloud platform. I added the gmail api and wrote some code :

 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();
      });

But I get an error (unauthorized_client) which I can't solve.

I hope you can help me or give me hints at least !

Pilum
  • 51
  • 1
  • 4

2 Answers2

1

Everything looks fine but make sure the following things :

  1. The correct OAuth2 scope for Gmail SMTP is https://mail.google.com/, make sure your client has this scope set when requesting permissions for an user.

  2. Make sure that Gmail API access is enabled for your Client ID. To do this, search for the Gmail API in Google API Manager and click on “enable”

Also, Make sure clientId and private key is being passed properly.

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37
1

Verify you follow these steps to be sure you set in the right way your client:

And then don't forget to enable your Gmail API as it is said here:

Also, I would recommend you to check the Gmail API Quickstart.

alberto vielma
  • 2,302
  • 2
  • 8
  • 15
  • I think i'm on the good way ! I did the last link you put and now i got a new error : invalid_grant, i'll search by myself. Thank you – Pilum Dec 02 '19 at 16:29
  • you're welcome! Consider mark my answer as the best answer if it helped you – alberto vielma Dec 02 '19 at 16:38
  • This is a great [https://www.freecodecamp.org/news/use-nodemailer-to-send-emails-from-your-node-js-server/](article) from freeCodeCamp. But, in the transport settings work for me is `service:'gmail', scope: 'https://mail.google.com', auth{type, user, clientId, ClientSecret, refreshToken, accessToken}` – Sabbir Sobhani Jun 01 '23 at 19:45