2019-01-22 08:55:35 +00:00
|
|
|
const nodemailer = require('nodemailer');
|
2019-10-29 06:46:44 +00:00
|
|
|
const config = require('./config');
|
2019-11-18 14:04:51 +00:00
|
|
|
const db = require('./database');
|
2019-01-22 08:55:35 +00:00
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
init() {
|
|
|
|
if (!this.transporter)
|
|
|
|
this.transporter = nodemailer.createTransport(config.smtp);
|
|
|
|
},
|
|
|
|
|
|
|
|
send(options) {
|
2019-11-18 14:04:51 +00:00
|
|
|
options.from = `${config.app.senderName} <${config.app.senderEmail}>`;
|
2019-01-22 08:55:35 +00:00
|
|
|
|
2019-09-30 11:02:11 +00:00
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
2019-10-29 06:46:44 +00:00
|
|
|
if (!config.smtp.auth.user)
|
2019-09-30 11:02:11 +00:00
|
|
|
return Promise.resolve(true);
|
|
|
|
|
2019-11-18 14:04:51 +00:00
|
|
|
options.to = config.app.senderEmail;
|
2019-09-30 11:02:11 +00:00
|
|
|
}
|
2019-01-22 08:55:35 +00:00
|
|
|
|
2019-11-18 14:04:51 +00:00
|
|
|
let error;
|
|
|
|
return this.transporter.sendMail(options).catch(err => {
|
|
|
|
error = err;
|
|
|
|
|
|
|
|
throw err;
|
|
|
|
}).finally(async() => {
|
2021-11-16 10:00:48 +00:00
|
|
|
const attachments = [];
|
|
|
|
for (let attachment of options.attachments) {
|
|
|
|
const fileName = attachment.filename;
|
|
|
|
const filePath = attachment.path;
|
2021-11-18 10:13:10 +00:00
|
|
|
if (fileName.includes('.png')) return;
|
2021-11-16 10:00:48 +00:00
|
|
|
|
|
|
|
if (fileName || filePath)
|
|
|
|
attachments.push(filePath ? filePath : fileName);
|
|
|
|
}
|
|
|
|
const fileNames = attachments.join(',\n');
|
2019-11-18 14:04:51 +00:00
|
|
|
await db.rawSql(`
|
2021-11-16 10:00:48 +00:00
|
|
|
INSERT INTO vn.mail (receiver, replyTo, sent, subject, body, attachment, status)
|
|
|
|
VALUES (?, ?, 1, ?, ?, ?, ?)`, [
|
2021-04-27 08:29:09 +00:00
|
|
|
options.to,
|
2021-07-22 06:39:15 +00:00
|
|
|
options.replyTo,
|
2021-04-27 08:29:09 +00:00
|
|
|
options.subject,
|
|
|
|
options.text || options.html,
|
2021-11-16 10:00:48 +00:00
|
|
|
fileNames,
|
2021-04-27 08:29:09 +00:00
|
|
|
error && error.message || 'Sent'
|
|
|
|
]);
|
2019-11-18 14:04:51 +00:00
|
|
|
});
|
2019-09-30 11:02:11 +00:00
|
|
|
}
|
2019-01-22 08:55:35 +00:00
|
|
|
};
|