No refresh token or refresh handler callback is set


I am trying to send Email using Nodemailer and OAuth2. It was working on localhost but not on Heroku so, I added OAuth to Nodemailer createTransport. But now it is not working even on localhost.

My code is:

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

const sendMail =async(email,code)=>{
    try
    {const accessToken = await oAuth2Client.getAccessToken();
    let transport = nodemailer.createTransport(smtTransport({
        service: "gmail",
        auth: {
            type:"OAuth2",
            user: "[email protected]",
            pass: process.env.EMAIL_PASS,
            clientId:process.env.CLIENT_ID,
            clientSecret:process.env.CLIENT_SECRET,
            refreshToken:process.env.REFRESH_TOKEN,
            accessToken:accessToken
        }
    }));

    let mailOptions,link;

   link = "http://localhost:5000"+email+"/"+code.toString() ;
    mailOptions={
        from:'"Horizons" <[email protected]>',
        to : email,
        subject: "Please verify your Email",
        html : "<h1>Horizons</h1><br><h2>Hi,<br> Please click on the link to verify your email.</h2><br><a href="+link+">Click here to verify</a>",
    }
    const result =await transport.sendMail(mailOptions);
    return result;

} catch(error){
    console.log(error);
}
    
}

I get the following error:

Error: No refresh token or refresh handler callback is set.
    at OAuth2Client.getAccessTokenAsync (E:horizons_blognode_modulesgoogle-auth-librarybuildsrcauthoauth2client.js:224:27)
    at OAuth2Client.getAccessToken (E:horizons_blognode_modulesgoogle-auth-librarybuildsrcauthoauth2client.js:209:25)
    at sendMail (file:///E:/horizons_blog/controllers/user.js:14:45)      
    at signUp (file:///E:/horizons_blog/controllers/user.js:78:9)
    at processTicksAndRejections (internal/process/task_queues.js:95:5) 

Source: JavaSript – Stack Overflow

September 10, 2021
Category : News
Tags: backend | javascript | node.js | nodemailer | oauth-2.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.