salix/print/core/email.js

90 lines
2.9 KiB
JavaScript

const path = require('path');
const smtp = require('./smtp');
const config = require('./config');
const Component = require('./component');
const Report = require('./report');
if (!process.env.OPENSSL_CONF)
process.env.OPENSSL_CONF = '/etc/ssl/';
class Email extends Component {
constructor(name, args) {
super(name);
this.args = args;
}
get path() {
return `../templates/email/${this.name}`;
}
async getSubject() {
return (await this.getUserLocale())['subject'];
}
/**
* @param {Object} [options] - Additional options
* @param {Boolean} [options.overrideAttachments] - Overrides default PDF attachments
* @param {Array} [options.attachments] - Array containing attachment objects
* @return {Promise} SMTP Promise
*/
async send(options = {}) {
const instance = this.build();
const rendered = await this.render();
const attachments = [];
const getAttachments = async(componentPath, files) => {
for (file of files) {
const fileCopy = Object.assign({}, file);
const fileName = fileCopy.filename;
if (options.overrideAttachments && !fileName.includes('.png')) continue;
if (fileCopy.cid) {
const templatePath = `${componentPath}/${file.path}`;
const fullFilePath = path.resolve(__dirname, templatePath);
fileCopy.path = path.resolve(__dirname, fullFilePath);
} else {
const reportName = fileName.replace('.pdf', '');
const report = new Report(reportName, this.args);
fileCopy.content = await report.toPdfStream();
fileCopy.filename = await report.getFileName();
}
attachments.push(fileCopy);
}
};
if (instance.components) {
const components = instance.components;
for (let componentName in components) {
const component = components[componentName];
const componentPath = `./components/${componentName}`;
await getAttachments(componentPath, component.attachments);
}
}
if (this.attachments)
await getAttachments(this.path, this.attachments);
if (options.attachments) {
for (let attachment of options.attachments)
attachments.push(attachment);
}
const localeSubject = await this.getSubject();
const replyTo = this.args.replyTo || this.args.auth.email;
const mailOptions = {
to: this.args.recipient,
replyTo: replyTo,
subject: localeSubject,
html: rendered,
attachments: attachments
};
return smtp.send(mailOptions);
}
}
module.exports = Email;