I am trying to call this function in another js file. This function should return the msg subject which you see towards the last part of the code. It returns undefined.
How to call this function so it returns the msg subject and lets store it in a variable?
Import statement used is correct:
import {getGmailData} from '../../Generic/Gmail.js
For example: let subject = getGmailData()
export async function getGmailData(){
await getOauthClient().then(async auth=> {
let gmail = google.gmail({
version: 'v1',
auth: auth
});
// Only get the recent email - 'maxResults' parameter
gmail.users.messages.list({userId: 'me', maxResults: 1}, async (err, response) => {
if (err) {
return console.log('The API returned an error: ' + err);
}
// Get the message id which we will need to retreive the actual message next.
const message_id = response['data']['messages'][0]['id'];
console.log("message id is:" +message_id)
// Retreive the actual message using the message id
gmail.users.messages.get({userId: 'me', 'id': message_id }, async (err, response) => {
if (err) {
return console.log('The API returned an error: ' + err);
}
// Access the email body content, like this...
let message_raw = response.data.payload.parts[0].body.data;
let data = message_raw;
var buff = await new Buffer.from(data, 'base64');
var text = await buff.toString();
//console.log("Email body is:" +text);
//Access the email subject as per below code:
let msgSubject = ''
let msgHeaders = response.data.payload.headers
//let headers = msgHeaders
for (let header of msgHeaders) {
if (header.name === 'Subject') {
msgSubject = header.value;
console.log(msgSubject)
**return msgSubject**
}
}
});
});
});
}