I am making a small application using node and the imap-simple and nodemailer library. I need that when I click on the download button, the email is downloaded in .eml format, which it already does, but the attached files are also downloaded in their corresponding formats.
i have this code and i try to extract attachments:
try {
const connection = await imaps.connect(config);
const fullSourcePath = folder.startsWith('INBOX') ? folder : `INBOX.${folder}`;
await connection.openBox(fullSourcePath);
const searchCriteria = [['UID', parseInt(uid)]];
const fetchOptions = {
bodies: ['HEADER', 'TEXT', ''],
struct: true
};
const results = await connection.search(searchCriteria, fetchOptions);
if (results.length === 0) {
return res.status(404).send('Correo no encontrado');
}
const email = results[0];
const emailBody = email.parts.filter(part => part.which === '')[0].body;
const saveEmailPath = path.resolve(__dirname, '../../../downloads', `email-${email.attributes.uid}.eml`);
fs.writeFile(saveEmailPath, emailBody, 'utf8', (err) => {
if (err) {
console.error('Error al guardar el archivo:', err);
return res.status(500).send('Error al guardar el archivo');
}
console.log(`Archivo guardado en ${saveEmailPath}`);
});
const attachments = [];
const findAttachments = (parts, parent) => {
parts.forEach(part => {
if (part.disposition && part.disposition.type.toUpperCase() === 'ATTACHMENT') {
attachments.push({
filename: part.disposition.params.filename,
encoding: part.encoding,
partID: part.partID,
body: parent || part
});
} else if (part.parts) {
findAttachments(part.parts, part);
}
});
};
findAttachments(email.parts);
if (attachments.length > 0) {
const attachmentPromises = attachments.map(async attachment => {
const part = await connection.getPartData(email, attachment);
const saveAttachmentPath = path.resolve(__dirname, '../../../downloads', attachment.filename);
return new Promise((resolve, reject) => {
fs.writeFile(saveAttachmentPath, part, 'base64', (err) => {
if (err) {
console.error('Error al guardar el adjunto:', err);
reject(err);
} else {
console.log(`Adjunto guardado en ${saveAttachmentPath}`);
resolve(saveAttachmentPath);
}
});
});
});
await Promise.all(attachmentPromises);
}
res.status(200).send('Correo y adjuntos descargados correctamente');
} catch (error) {
console.error('Error descargando correo', error);
res.status(500).send('Error descargando correo');
}
});
New contributor
Bea9495 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.