Skip to content

Commit

Permalink
added gettext method for gmail api
Browse files Browse the repository at this point in the history
  • Loading branch information
andris9 committed Jan 16, 2024
1 parent 6ca4a91 commit 0ff2444
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions lib/api-client/gmail-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,66 @@ class GmailClient {

return result;
}

async getText(textId, options) {
options = options || {};
await this.prepare();

const accessToken = await this.getToken();

const [messageId, textParts] = msgpack.decode(Buffer.from(textId, 'base64url'));

const bodyParts = new Map();

textParts[0].forEach(p => {
bodyParts.set(p, 'text');
});

textParts[1].forEach(p => {
bodyParts.set(p, 'html');
});

const requestQuery = {};
const messageData = await this.oAuth2Client.request(
accessToken,
`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${messageId}?format=full`,
'get',
requestQuery
);

const response = {};

if (options.textType && options.textType !== '*') {
response[options.textType] = '';
}

const textContent = {};
const walkBodyParts = node => {
let textType = bodyParts.has(node.partId) ? bodyParts.get(node.partId) : false;

if (textType && (options.textType === '*' || options.textType === textType) && node.body?.data) {
if (!textContent[textType]) {
textContent[textType] = [];
}
textContent[textType].push(Buffer.from(node.body.data, 'base64'));
}

if (Array.isArray(node.parts)) {
for (let part of node.parts) {
walkBodyParts(part);
}
}
};
walkBodyParts(messageData.payload);

for (let key of Object.keys(textContent)) {
response[key] = textContent[key].map(buf => buf.toString()).join('\n');
}

response.hasMore = false;

return response;
}
}

module.exports = { GmailClient };
Expand All @@ -539,6 +599,9 @@ let main = async () => {
if (msg.attachments && msg.attachments.length) {
await gmailClient.getMessage(msg.id, { textType: '*' });

const textContent = await gmailClient.getText(msg.text.id, { textType: '*' });
console.log('TEXT CONTENT', textContent);

let raw = await gmailClient.getRawMessage(msg.id);
await fs.promises.writeFile(`/Users/andris/Desktop/${msg.id}.eml`, raw);
for (let a of msg.attachments) {
Expand Down

0 comments on commit 0ff2444

Please sign in to comment.