I’m working on retrieving email content and headers from Gmail messages. Currently, I need to make separate API calls for each message to get the full body text, which makes my application really slow.
Here’s what I’m currently doing:
const result = await gmail.users.messages.list({
userId: "me",
maxResults: messageLimit,
pageToken: currentPageToken,
includeSpamTrash: false,
});
// Trying these helper functions to get message content
function getMessageText(
messagePart: GmailV1.Schema$MessagePart | undefined
): string | null {
if (!messagePart) {
return null;
}
if (messagePart.mimeType === "text/plain") {
const content = messagePart.body?.data ?? "";
return Buffer.from(content, "base64").toString("utf8");
} else if (messagePart.mimeType === "multipart/alternative") {
for (const section of messagePart.parts!) {
const content = getMessageText(section);
if (content) {
return content;
}
}
}
return "";
}
function extractContent(email: GmailV1.Schema$Message) {
const structure = email?.payload;
let content = "";
const bodyData = structure?.parts ? structure.parts[1].body : structure?.body;
if (bodyData?.data) {
const decoded = Buffer.from(bodyData.data, "base64");
content = decoded.toString("utf-8");
}
if (bodyData?.attachmentId) {
const textContent = structure?.parts[0]?.parts[1]?.body?.data;
if (textContent) {
const decoded = Buffer.from(textContent, "base64");
content = decoded.toString("utf-8");
}
}
return content;
}
I read that Gmail API supports batch operations. Could this help me get all message bodies at once? Any examples using the googleapis library would be helpful.