read-email-cg-lib
Version:
Library to read emails
160 lines (148 loc) • 5.28 kB
JavaScript
const Imap = require('imap');
const {simpleParser} = require('mailparser');
const {constants, log, helpers} = require('utils-nxg-cg');
const {isObjectValid} = require("utils-nxg-cg/utils/helpers");
const {attach: attachProps, email: emailProps} = require('./objects');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
/**
* Global variables
*/
let response = [];
let arrayParsed = [];
/**
* emailTransform
* @param properties
* @returns {Promise<*[]>}
*/
const emailTransform = async (properties) => {
try {
if (properties.timeZone !== "") {
helpers.setTimeZone(properties.timeZone)
}
const imapConfig = {
user: properties.user,
password: properties.password,
host: properties.host,
port: properties.port,
tls: properties.tls,
tlsOptions: {
rejectUnauthorized: false
}
};
arrayParsed = [];
response = [];
response = await processMails(imapConfig, properties);
if (!isObjectValid(response)) {
throw Error(constants.ERROR_JSON_FORMAT);
}
return response;
} catch (e) {
throw Error(e);
} finally {
if (properties.timeZone !== "") {
helpers.removeCustomTimeZone();
}
}
};
/**
* Process emails
* @param imapConfig
* @param properties
* @returns {Promise<*[]>}
*/
async function processMails(imapConfig, properties) {
await getMails(imapConfig, properties);
if (properties.sortDate === "desc") {
arrayParsed.sort(function (a, b) {
return (b.date - a.date);
});
} else if (properties.sortDate === "asc") {
arrayParsed.sort(function (a, b) {
return (a.date - b.date);
});
}
arrayParsed.forEach(parsed => {
const email = {...emailProps};
const attachArray = [];
email.subject = parsed.subject;
email.from = parsed.from.value;
email.to = parsed.to.value;
email.text = parsed.text;
email.date = parsed.date.toLocaleDateString(properties.dateFormat);
if (parsed.attachments.length > 0) {
parsed.attachments.forEach(attachment => {
const attach = {...attachProps};
attach.filename = attachment.filename;
attach.contentType = attachment.contentType;
attach.content = attachment.content.toString('base64')
attachArray.push(attach);
});
email.attachments = attachArray;
}
//log.info(email);
response.push(email);
});
return response;
}
/**
* Get emails
* @param imapConfig
* @param properties
* @returns {Promise<unknown>}
*/
function getMails(imapConfig, properties) {
return new Promise((resolve) => {
//arrayParsed=[];
const imap = new Imap(imapConfig);
imap.once('ready', () => {
imap.openBox('INBOX', false, () => {
const eDate = new Date(properties.endDate);
eDate.setDate(eDate.getDate() + 1);
imap.search([properties.status, ['SINCE', properties.startDate], ['BEFORE', eDate]], (err, results) => {
if (err) {
throw Error(err);
}
//log.info(results);
if (results.length > 0) {
const f = imap.fetch(results, {bodies: ''});
f.on('message', msg => {
//console.log('Message #%d', seqno);
msg.on('body', stream => {
simpleParser(stream, async (err, parsed) => {
arrayParsed.push(parsed);
});
});
msg.once('attributes', attrs => {
const {uid} = attrs;
imap.addFlags(uid, ['\\Seen'], () => {
// Mark the email as read after reading it
//log.info('Marked as read!');
});
});
});
f.once('error', ex => {
return Promise.reject(ex);
});
f.once('end', () => {
// log.info('Done fetching all messages!');
imap.end();
});
} else {
// log.info("No emails available");
resolve("No emails available");
}
});
});
}).on('end', () => {
log.info('Connection ended');
}).on('error', err => {
log.error(err);
});
imap.connect();
setTimeout(() => {
resolve();
}, 6000
);
});
}
module.exports = {emailTransform};