Skip to content

Instantly share code, notes, and snippets.

@diegofcornejo
Created December 16, 2024 20:27
Show Gist options
  • Save diegofcornejo/95a18a234430f6ac9360e2a87abcae59 to your computer and use it in GitHub Desktop.
Save diegofcornejo/95a18a234430f6ac9360e2a87abcae59 to your computer and use it in GitHub Desktop.
Download attachments from EML file
const EmlParser = require('eml-parser');
const fs = require('fs');
const path = require('path');
// Define paths
const filesPath = 'files';
const resultsPathPrefix = 'results';
const timestamp = new Date().toISOString().replace(/[:]/g, '-').split('.')[0];
const resultsPath = path.join(resultsPathPrefix, timestamp);
const createDirectory = (dirPath) => {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
};
createDirectory(resultsPath);
const saveAttachment = (attachment) => {
const filePath = path.join(resultsPath, attachment.filename);
fs.writeFileSync(filePath, attachment.content);
console.log(`Attachment saved: ${filePath}`);
};
const getAttachments = (emlFilePath) => {
return new Promise((resolve, reject) => {
const file = fs.createReadStream(emlFilePath);
new EmlParser(file)
.getEmailAttachments({ ignoreEmbedded: true })
.then((attachments) => {
attachments.forEach((attachment) => {
console.log(`Processing attachment: ${attachment.filename}`);
saveAttachment(attachment);
});
resolve();
})
.catch((err) => {
console.error(`Error processing file: ${emlFilePath}`, err.message);
reject(err);
});
});
};
const files = fs.readdirSync(filesPath);
for (const file of files) {
console.log('==============================================');
console.log('Email:', file);
const emlFilePath = path.join(filesPath, file);
try {
getAttachments(emlFilePath).then(() => {
console.log(`Finished processing: ${file}`);
});
} catch (error) {
console.error(`Error processing email: ${file}`, error.message);
}
console.log('==============================================');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment