eml2png
Version:
Paint the EML to a single PNG image.
93 lines (85 loc) • 2.87 kB
JavaScript
;
const fs = require('fs');
const stream = require('stream');
const wkhtmltox = require('wkhtmltox');
const simpleParser = require('mailparser').simpleParser;
const MailParser = require('mailparser2-mit').MailParser;
function eml2png(opts) {
const self = this;
self.converter = new wkhtmltox(opts || {
interval: 10,
maxWorkers: 0
});
self.converter.wkhtmltoimage = process.env.WKHTMLTOIMAGE || 'wkhtmltoimage';
function isFile(path) {
try {
return fs.lstatSync(path).isFile();
} catch (e) {
return false;
}
};
/**
* Get HTML text from EML file.
*
* @param {string} input
* @returns {Promise}
*/
self.getHtmlStrFromFile = async (input) => {
const emlContent = isFile(input) ? fs.createReadStream(input) : input;
const parse = await simpleParser(emlContent);
const html = parse.html;
const textAsHtml = parse.textAsHtml;
const text = parse.text;
if (html === false && !textAsHtml && !text) {
const fallbackContent = await new Promise((resolve, reject) => {
const mailparser = new MailParser({
defaultCharset: 'utf8'
});
mailparser.on('end', (mailObject) => {
resolve(mailObject.html || mailObject.text);
});
if (isFile(input)) {
fs.createReadStream(input).pipe(mailparser);
} else {
mailparser.write(input);
mailparser.end();
}
});
return fallbackContent || undefined;
}
return html == false ? (textAsHtml || text) : html;
};
/**
* Convert a EML file or string to PNG file.
*
* @param {string} input
* @param {*} [options={}]
* @param {string} outputPath
* @returns {Promise}
*/
self.png = async (input, options = {}, outputPath) => {
const htmlContent = await self.getHtmlStrFromFile(input);
if (!htmlContent) {
return undefined;
}
const emlHtml = new stream.PassThrough();
emlHtml.write(htmlContent);
emlHtml.end();
options = options || {};
options.format = 'png';
const pngStream = self.converter.image(emlHtml, options);
if (outputPath) {
const isDone = await new Promise((resolve, reject) => {
pngStream.pipe(fs.createWriteStream(outputPath)).on('finish', () => {
resolve(true);
}).on('error', () => {
resolve(false);
});
});
return isDone ? outputPath : undefined;
}
return pngStream;
};
return self;
}
module.exports = eml2png;