0

I was trying to send an email from my nodejs server using the nodemailer and OAuth 2 from a web app I'm working on

The code was fine and the mails were being sent as they should be but today when I tried to send mails this error occurred on the server-side as the front end was working fine.

This is my server code:

const express = require('express')

const app = express()
const bodyParser = require('body-parser')
const hb = require('nodemailer-express-handlebars')
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
 const nodemailer = require('nodemailer');
 const { google } = require('googleapis');
 const path = require('path');

// These id's and secrets should come from .env file.
 const CLIENT_ID = 'client i_d';
 const CLEINT_SECRET = 'client secret';
 const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
 const REFRESH_TOKEN = 'refresh token**strong text**';

 const oAuth2Client = new google.auth.OAuth2(
   CLIENT_ID,
   CLEINT_SECRET,
   REDIRECT_URI
 );
 oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

//query ajaxx
app.post("/query", async (req,res) =>{
    try{
        const accessToken = await oAuth2Client.getAccessToken();
    
        const transport = nodemailer.createTransport({
          service: 'gmail',
          auth: {
            type: 'OAuth2',
            user: 'ummed.gagrana@gmail.com',
            clientId: CLIENT_ID,
            clientSecret: CLEINT_SECRET,
            refreshToken: REFRESH_TOKEN,
            accessToken: accessToken,
          },
        })
        
        const handlebarOptions = {
            viewEngine: {
              extName: ".handlebars",
              partialsDir: path.resolve(__dirname, "emailTemplate"),
              defaultLayout: false,
            },
            viewPath: path.resolve(__dirname, "emailTemplate"),
            extName: ".handlebars",
          };
          
          transport.use(
            "compile",
            hb(handlebarOptions)
          );
    
       // the data which we gonna send
            
        const responseMail = {
            from: "The Ummed Gagrana"+'<ummed.gagrana@gmail.com>',
            to: req.body.user.Qemail,
            subject: "We will get back to you soon!!",
            //   html: '<h2>From:</h2>'+'<h4>'+req.body.email+"</h4> <br>"+"<h2>Message:</h2>"+'<h4>'+req.body.message+"</h4>",
            template: 'comeBack',
            context: {                  // <=
                name: req.body.user.Qname,     
              }
        };
        const receiveMail = {
            from: req.body.email+"<ummed.gagrana@gmail.com>",
            to: "ummed.gagrana@gmail.com",
            subject: "Room enquiry",
            template:'query',
            context: { 
                // user details

                name:  req.body.user.Qname,
                email: req.body.user.Qemail ,
                msg:   req.body.user.Qmessage,
                phone: req.body.user.Qphone,

                //the query details
                
                accomodation: req.body.query.room,
                stay: req.body.query.time,
                budget: req.body.query.budget
              }
        }
       //sending mail
    
           const Sresult = await transport.sendMail(responseMail);
           const Rresult = await transport.sendMail(receiveMail);
    
       // checking the result after sending mail
            console.log(Sresult)
            console.log(Rresult)
            res.send({datapassed:"We have received your query!"})
    
          } catch (error) {
            console.log(error)
            res.send({datapassed:"There was some error try again later"})
          }
    })
    

//contact ajax 
app.post("/api", async (req,res) => {
    try{
    const accessToken = await oAuth2Client.getAccessToken();

    const transport = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        type: 'OAuth2',
        user: 'ummed.gagrana@gmail.com',
        clientId: CLIENT_ID,
        clientSecret: CLEINT_SECRET,
        refreshToken: REFRESH_TOKEN,
        accessToken: accessToken,
      },
    })
    
    const handlebarOptions = {
        viewEngine: {
          extName: ".handlebars",
          partialsDir: path.resolve(__dirname, "emailTemplate"),
          defaultLayout: false,
        },
        viewPath: path.resolve(__dirname, "emailTemplate"),
        extName: ".handlebars",
      };
      
      transport.use(
        "compile",
        hb(handlebarOptions)
      );

   // the data which we gonna send
        
    const responseMail = {
        from: "The Ummed Gagrana"+'<ummed.gagrana@gmail.com>',
        to: req.body.email,
        subject: "We will get back to you soon!!",
        //   html: '<h2>From:</h2>'+'<h4>'+req.body.email+"</h4> <br>"+"<h2>Message:</h2>"+'<h4>'+req.body.message+"</h4>",
        template: 'comeBack',
        context: {                  // <=
            name: req.body.name,     
          }
    };

    const receiveMail = {
        from: req.body.email+"<ummed.gagrana@gmail.com>",
        to: "ummed.gagrana@gmail.com",
        subject: req.body.subject,
        text: "From:" + req.body.email + "\n Message:" + req.body.message,
        template:'receive',
        context: {                  // <=
            name:  req.body.name,
            email: req.body.email ,
            msg:   req.body.message,
          }
    }
   //sending mail

       const Sresult = await transport.sendMail(responseMail);
       const Rresult = await transport.sendMail(receiveMail);

   // checking the result after sending mail
        console.log(Sresult)
        console.log(Rresult)
        res.send({datapassed:"we have received your mail!"})

      } catch (error) {
        console.log(error)
        res.send({datapassed:"there was some error try again later"})
      }
    
})

app.listen(3000, () => {
    console.log("server up and running on port 3000")
})

The client id and the refresh tokens are all correct I've tried to refresh the refresh token but still getting the same error I will show you the full log of the error

the terminal log

I really don't have any idea what am I missing it would be a great help and please ignore my untidy code I'm a beginner thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0
  1. Follow the steps from https://medium.com/@nickroach_50526/sending-emails-with-node-js-using-smtp-gmail-and-oauth2-316fe9c790a1

  2. Generate gmail password from https://myaccount.google.com/?hl=en&utm_source=OGB&utm_medium=act

Security > Search for App password > select app > select device (Windows computer) > and click generate

  1. make sure from google console > oauth consent > you have added your test users' emails (here include current logged email)

  2. test your code again

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/34660879) – sanitizedUser Jul 11 '23 at 23:10