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);
|
|
|
|
},
|
|
|
|
|
2022-11-09 13:51:30 +00:00
|
|
|
async 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') {
|
2022-11-09 13:51:30 +00:00
|
|
|
const notProductionError = {message: 'This not production, this email not sended'};
|
|
|
|
await this.mailLog(options, notProductionError);
|
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
|
|
|
|
2023-06-23 18:03:56 +00:00
|
|
|
let res;
|
2019-11-18 14:04:51 +00:00
|
|
|
let error;
|
2023-06-23 18:03:56 +00:00
|
|
|
try {
|
|
|
|
res = await this.transporter.sendMail(options);
|
|
|
|
} catch (err) {
|
2019-11-18 14:04:51 +00:00
|
|
|
error = err;
|
|
|
|
throw err;
|
2023-06-23 18:03:56 +00:00
|
|
|
} finally {
|
2022-11-09 13:51:30 +00:00
|
|
|
await this.mailLog(options, error);
|
2023-06-23 18:03:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
2022-11-09 13:51:30 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
async mailLog(options, error) {
|
|
|
|
const attachments = [];
|
|
|
|
if (options.attachments) {
|
|
|
|
for (let attachment of options.attachments) {
|
|
|
|
const fileName = attachment.filename;
|
|
|
|
const filePath = attachment.path;
|
|
|
|
if (fileName.includes('.png')) continue;
|
|
|
|
|
|
|
|
if (fileName || filePath)
|
|
|
|
attachments.push(filePath ? filePath : fileName);
|
2021-11-16 10:00:48 +00:00
|
|
|
}
|
2022-11-09 13:51:30 +00:00
|
|
|
}
|
2022-01-18 12:15:42 +00:00
|
|
|
|
2022-11-09 13:51:30 +00:00
|
|
|
const fileNames = attachments.join(',\n');
|
|
|
|
|
|
|
|
await db.rawSql(`
|
2023-06-22 05:49:35 +00:00
|
|
|
INSERT INTO vn.mail
|
|
|
|
SET receiver = ?,
|
|
|
|
replyTo = ?,
|
|
|
|
sent = ?,
|
|
|
|
subject = ?,
|
|
|
|
body = ?,
|
|
|
|
attachment = ?,
|
|
|
|
status = ?`, [
|
2022-11-09 13:51:30 +00:00
|
|
|
options.to,
|
|
|
|
options.replyTo,
|
2023-06-22 05:49:35 +00:00
|
|
|
error ? 2 : 1,
|
2022-11-09 13:51:30 +00:00
|
|
|
options.subject,
|
|
|
|
options.text || options.html,
|
|
|
|
fileNames,
|
2023-06-22 05:49:35 +00:00
|
|
|
error && error.message || 'OK'
|
2022-11-09 13:51:30 +00:00
|
|
|
]);
|
2019-09-30 11:02:11 +00:00
|
|
|
}
|
2022-11-09 13:51:30 +00:00
|
|
|
|
2019-01-22 08:55:35 +00:00
|
|
|
};
|