@szegedsw/lib-node
Version:
A little framework published by Szeged Software Zrt. in order to enhance api endpoint security and create reuseable code. Email module, Logging system, and much more. Further improvements are expected.
172 lines • 8.06 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmailService = exports.MailPriority = void 0;
const lodash_1 = __importDefault(require("lodash"));
const nodemailer_1 = require("nodemailer");
const config_1 = require("../config/config");
const logger_1 = require("../logger/logger");
// eslint-disable-next-line no-shadow
var MailPriority;
(function (MailPriority) {
MailPriority["high"] = "high";
MailPriority["normal"] = "normal";
MailPriority["low"] = "low";
})(MailPriority = exports.MailPriority || (exports.MailPriority = {}));
let EmailService = /** @class */ (() => {
class EmailService {
/**
* @description Use this function if you are using a supported service of nodemailer.
* @param service one of listed here: https://nodemailer.com/smtp/well-known/
* @param user email account username
* @param password email account password
* @param defaultRecipients default list of recipients
* @param allowEmail flag for allowing email sending by default
*/
static configEmailService(service = "", user = "", password = "", allowEmail = true) {
if (service && user && password) {
if (!this.mailers[user]) {
this.mailers[user] = { transporter: nodemailer_1.createTransport({ service, auth: { user, pass: password } }), allowEmail };
}
else {
logger_1.Logger.info(`EmailService found transporter for user ${user}`);
}
if (!this.mailers[user].transporter) {
this.mailers[user].allowEmail = false;
logger_1.Logger.warning("EmailService could not create transporter... Please check the passed paramaters!");
}
else if (this.mailers[user]) {
this.mailers[user].allowEmail = allowEmail && true;
logger_1.Logger.info("EmailService configured successfully!");
}
}
else {
if (this.mailers[user]) {
this.mailers[user].allowEmail = false;
}
logger_1.Logger.error("EmailService service|user|password is empty!");
}
}
/**
* @description Use this function if you are using an individual mail server not listed in supported services of nodemailer.
* @param allowEmail flag for allowing email sending by default
*/
static configEmailTransport(options, allowEmail = true) {
const user = this.createTransport(options);
if (!this.mailers[user].transporter) {
this.mailers[user].allowEmail = false;
logger_1.Logger.warning(`EmailService for user '${user}' could not create transporter... Please check the passed paramaters!`);
}
else {
this.mailers[user].allowEmail = allowEmail && true;
logger_1.Logger.info(`EmailService for user '${user}' configured successfully!`);
}
}
static async sendDefaultMail(to, subject, text, priority, isHtml = false, attachments) {
return this.sendMail(config_1.env.emailUser, to, subject, text, priority, isHtml, attachments);
}
static async sendEventEmail(event, text, attachments) {
if (config_1.env.emailEvents.includes(event)) {
text = `Server event happened: ${event}\n${text}`;
await this.sendMail(config_1.env.emailUser, config_1.env.emailAdmins, `${config_1.env.emailSubject} - ${event}`, text, MailPriority.high, false, attachments);
}
}
/**
* @param from email user, from where email will be sent
* @param recipients addresses of recipients
* @param subject email subject
* @param html formatted including parameters
* @param parameters object of parameters included in mail html, for replacement of values
*/
static async sendNiceMail(from, recipients, subject, html, parameters) {
if (!recipients.length) {
return;
}
Object.keys(parameters).forEach((key) => {
html = lodash_1.default.replace(html, new RegExp(`_${key}`, "g"), parameters[key]);
subject = lodash_1.default.replace(subject, new RegExp(`_${key}`, "g"), parameters[key]);
});
// eslint-disable-next-line consistent-return
return this.sendMail(from, recipients, subject, html, MailPriority.normal, true);
}
static async sendMail(from, to, subject, text, priority, isHtml = false, attachments) {
return new Promise((resolve) => {
var _a;
if ((_a = this.mailers[from]) === null || _a === void 0 ? void 0 : _a.allowEmail) {
const mailOptions = {
from,
disableFileAccess: true,
disableUrlAccess: true,
to,
subject,
html: isHtml ? text : undefined,
text: isHtml ? undefined : text,
priority,
attachments,
replyTo: config_1.env.emailReplyTo || undefined,
};
this.mailers[from].transporter.sendMail(mailOptions, (err) => {
if (err) {
logger_1.Logger.error(`Error occured while sending mail... : ${err.message}`);
resolve(false);
}
else {
resolve(true);
}
});
}
else {
resolve(undefined);
}
});
}
static closeTransports() {
Object.keys(this.mailers).forEach((m) => {
if (this.mailers[m].transporter) {
this.mailers[m].transporter.close();
}
});
}
static createTransport(options) {
var _a;
const user = ((_a = options === null || options === void 0 ? void 0 : options.auth) === null || _a === void 0 ? void 0 : _a.user) || config_1.env.emailUser;
if (!this.mailers[user]) {
this.mailers[user] = {
transporter: nodemailer_1.createTransport(options || {
pool: true,
host: config_1.env.emailHost,
port: config_1.env.emailPort,
secure: config_1.env.emailSecure,
auth: {
type: "LOGIN",
user: config_1.env.emailUser,
pass: config_1.env.emailPassword,
},
logger: config_1.env.emailLogger,
debug: logger_1.Logger.level >= logger_1.LogLevel.trace,
maxConnections: config_1.env.emailPoolSize,
tls: {
rejectUnauthorized: config_1.env.emailRejectUnauthorized,
},
}),
allowEmail: true,
};
}
else {
logger_1.Logger.info(`EmailService found transporter for user ${user}`);
}
return user;
}
}
Object.defineProperty(EmailService, "mailers", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
return EmailService;
})();
exports.EmailService = EmailService;
//# sourceMappingURL=email.service.js.map