`async fetch_pdf_attachment(from_email, to_address, subject, body, downloadPath = "./Data/Files/") { let count = 0; let email = null;
// Get access token
const accessToken = await getAccessToken(
gmail_data.CLIENT_ID,
gmail_data.CLIENT_SECRET,
gmail_data.REFRESH_TOKEN,
);
// Retry mechanism to find the email
do {
email = await checkInbox({
token: accessToken,
query: `from:${from_email} to:${to_address} subject:${subject} ${body} has:attachment`,
format: 'full' // Request full message format to get all parts
});
if (!email) {
count += 1;
console.log(`Email not found, retrying (${count}/5)...`);
await CommonUtils.sleep(5);
}
} while (!email && count < 5);
if (!email) {
console.log("No matching email found after retries.");
return null;
}
// Ensure the download directory exists
if (!fs.existsSync(downloadPath)) {
fs.mkdirSync(downloadPath, { recursive: true });
}
try {
// Find the PDF attachment part
let pdfPart = null;
// Function to find PDF part in message structure
function findPdfPart(part) {
if (part.mimeType === 'application/pdf' && part.body && part.body.attachmentId) {
return part;
}
if (part.parts) {
for (const subpart of part.parts) {
const found = findPdfPart(subpart);
if (found) return found;
}
}
return null;
}
// Start search from the message payload
pdfPart = findPdfPart(email.payload);
if (!pdfPart) {
console.log("No PDF attachment found in the email.");
return null;
}
console.log(`Found PDF attachment: ${pdfPart.filename || 'unnamed.pdf'}`);
// Get the attachment data
const attachmentData = await checkInbox({
token: accessToken,
messageId: email.id,
attachmentId: pdfPart.body.attachmentId
});
if (!attachmentData || !attachmentData.data) {
console.log("Could not retrieve attachment data.");
return null;
}
// Save the PDF file
const filename = pdfPart.filename || 'attachment.pdf';
const filePath = path.join(downloadPath, filename);
const decodedData = Buffer.from(attachmentData.data, 'base64');
fs.writeFileSync(filePath, decodedData);
console.log(`PDF saved at: ${filePath}`);
return filePath;
} catch (error) {
console.error(`Error processing email attachment: ${error.message}`);
return null;
}
}`
What modification’s need to be done to get the attachments from the email, The current code is going nested. It's having an nested mime structure . how to overcome this
It's finding the part which has the attachment application/pdf, even then using the attachment id was trying to retrieve the data, but again that part is having two parts one is text/html and application/pdf. It's going nested and becoming an infinite loop.