73 lines
2.0 KiB
JavaScript
73 lines
2.0 KiB
JavaScript
const nodemailer = require('nodemailer');
|
|
const config = require('./config');
|
|
const db = require('./database');
|
|
|
|
module.exports = {
|
|
init() {
|
|
if (!this.transporter)
|
|
this.transporter = nodemailer.createTransport(config.smtp);
|
|
},
|
|
|
|
async send(options) {
|
|
options.from = `${config.app.senderName} <${config.app.senderEmail}>`;
|
|
if (!process.env.NODE_ENV)
|
|
options.to = config.app.senderEmail;
|
|
|
|
if (process.env.NODE_ENV !== 'production' && !options.force) {
|
|
const notProductionError = {message: 'This not production, this email not sended'};
|
|
await this.mailLog(options, notProductionError);
|
|
}
|
|
|
|
if (!config.smtp.auth.user)
|
|
return Promise.resolve(true);
|
|
|
|
let res;
|
|
let error;
|
|
try {
|
|
res = await this.transporter.sendMail(options);
|
|
} catch (err) {
|
|
error = err;
|
|
throw err;
|
|
} finally {
|
|
await this.mailLog(options, error);
|
|
}
|
|
|
|
return res;
|
|
},
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
const fileNames = attachments.join(',\n');
|
|
|
|
await db.rawSql(`
|
|
INSERT INTO vn.mail
|
|
SET receiver = ?,
|
|
replyTo = ?,
|
|
sent = ?,
|
|
subject = ?,
|
|
body = ?,
|
|
attachment = ?,
|
|
status = ?`, [
|
|
options.to,
|
|
options.replyTo,
|
|
error ? 2 : 1,
|
|
options.subject,
|
|
options.text || options.html,
|
|
fileNames,
|
|
error && error.message || 'OK'
|
|
]);
|
|
}
|
|
|
|
};
|