I am using the Google API library in Node.js to fetch emails from Gmail. The code snippet below demonstrates how I retrieve and extract data from the fetched message:
const gmail = google.gmail({ version: "v1", auth: oAuth2Client });
const messageId = req.params.id;
const message = await gmail.users.messages.get({
userId: "me",
id: messageId,
format: "full",
});
// Extract the required data from the message
const isRead = !message.data.labelIds.includes("UNREAD");
const snippet = message.data.snippet.trim();
const email = {
id: message.data.id,
subject: message.data.payload.headers.find(
(header) => header.name === "Subject"
).value,
from: message.data.payload.headers
.find((header) => header.name === "From")
.value.split("<")[0],
date: moment(
message.data.payload.headers.find((header) => header.name === "Date").value
).format("MM/DD/YYYY, hh:mm a"),
snippet,
isRead,
message: Buffer.from(message.data.payload.parts[0].body.data,
"base64").toString("utf-8"),
};
The above code successfully fetches the email, and extracts essential information such as the subject, sender, date, and message content. However, the extracted message is in raw format, and I'm unable to preserve the original formatting and layout seen in the Gmail interface.
I want to render the email with the same design that users see when they access Gmail through the web interface or the official app. How can I achieve this formatting for the fetched messages?
Any insights or suggestions on how to improve the code to achieve the desired Gmail-like formatting would be highly appreciated. Thank you in advance!