I am trying to read one particular email from my Gmail inbox using Gmail API.
// Load client secrets from a local file.
fs.readFile('credential/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), listMessages);
});
function listMessages(oauth2Client, userId, query, callback) {
const gmail = google.gmail('v1');
gmail.users.messages.list({
'auth': oauth2Client,
'userId': userId,
'q': query
}, (err, resp) => {
if(err) return console.log(err);
callback(oauth2Client, JSON.stringify(resp.data.messages[0].id));
});
}
function getMessage(oauth2Client, messageId, callback) {
const gmail = google.gmail('v1');
let base64 = require('js-base64').Base64;
console.log(messageId);
gmail.users.messages.get({
'auth': oauth2Client,
'userId': 'me',
'id': messageId
}, (err, resp) => {
if(err) return console.log(err);
//console.log(resp);
//console.log(base64.decode(resp.payload.body.data.replace(/-/g, '+').replace(/_/g, '/')));
});
}
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, "me", "Daily Coding Problem", getMessage);
});
}
I keep getting the following error message after getMessage() is called.
errors: [
{
domain: 'global',
reason: 'invalidArgument',
message: 'Invalid id value'
}
]
I tried using Gmail API directly by filling in the form below and I did get the message I was expecting. The Id I used was copied and pasted directly from messageId from getMessage() function. I do not understand why the same Id string was considered invalid by Gmail messages.get() function.
In this line of code:
callback(oauth2Client, JSON.stringify(resp.data.messages[0].id));
JSON.stringify()
is adding extra "
marks to the messageId
thereby making it invalid. The response from gmail.users.messages.list()
returns an array of objects with the messageId
as a string so there is no need to stringify it.