Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_blog\node_modules\google-auth-library\build\src\auth\oauth2client.js:224:27)
    at OAuth2Client.getAccessToken (E:\horizons_blog\node_modules\google-auth-library\build\src\auth\oauth2client.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) 
like image 746
Naman Kedia Avatar asked Jun 12 '26 18:06

Naman Kedia


1 Answers

The problem is process.env.REFRESH_TOKEN isn't being populated mostly because you haven't configured dotenv.

Add this to populate it:

import dotenv from "dotenv";

// *Useful for getting environment vairables
dotenv.config();
like image 50
Abdi mussa Avatar answered Jun 15 '26 12:06

Abdi mussa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!