I’m working on a project where a user registers and grants full access to the site. After obtaining the access token, I’m trying to send an email using SMTP, but I keep encountering an error related to “grant type.” I’m unable to send the email, and the error message I’m seeing is something like:
Error: Invalid grant type
or Error: Grant type not allowed for this request
I have checked the grant type in the OAuth2 flow and verified that I am using the correct token, but it seems that the SMTP server still rejects the request. I’ve also tried different SMTP ports and ensured that the token is valid, but the issue persists
import fetch from 'node-fetch';
const refreshAccessToken = async (refreshToken, clientId, clientSecret) => {
console.log('Refreshing token with refreshToken:', refreshToken);
try {
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: 'refresh_token',
}),
});
const data = await response.json();
if (data.error) {
console.error('Refresh token error:', data.error);
throw new Error(`Failed to refresh token: ${data.error}`);
}
console.log('New Access Token:', data.access_token);
return data.access_token;
} catch (error) {
console.error('Error refreshing access token:', error.message);
throw error;
}
};
// Example function for email
const sendEmail = async (userEmail, refreshToken, clientId, clientSecret, to, subject, body) => {
try {
const accessToken = await refreshAccessToken(refreshToken, clientId, clientSecret);
console.log('Access Token Retrieved:', accessToken);
// Your email sending logic here...
} catch (error) {
console.error('Failed to send email:', error.message);
}
};
Mohammad Usman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.