I have a requirement in which I want to read specific emails from inbox of the users of my applications. I have created a project in google console and add Gmail API. Now I am able to read my own emails using it. but I am not getting how can I authenticate my users and will be able to read their emails from my application. My Application is in Nodejs.
For every operation I want to perform for another user I am getting :
The API returned an error: Error: Delegation denied for
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Gmail API.
authorize(JSON.parse(content), getRecentEmail);
});
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function getRecentEmail(auth) {
// Only get the recent email - 'maxResults' parameter
gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 10,}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
// Get the message id which we will need to retreive tha actual message next.
var message_id = response['data']['messages'][0]['id'];
// Retreive the actual message using the message id
//https://gmail.googleapis.com/gmail/v1/users/{userId}/settings/delegates
gmail.users.messages.get({auth: auth, userId: 'me', 'id': message_id}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response['data']);
let message_raw = response['data']['payload']['parts'][0].body.data;
let data = message_raw;
let buff = new Buffer(data, 'base64');
let text = buff.toString();
});
});
}
If I am adding any other mail id in UserId i am getting the error."The API returned an error: Error: Delegation denied for "
Please help me out or suggest if I can use something else to achieve this.