-
Notifications
You must be signed in to change notification settings - Fork 6
/
mailer.js
102 lines (89 loc) · 2.76 KB
/
mailer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const nodemailer = require('nodemailer');
const path = require('path');
const fs = require('fs');
let smtp = nodemailer.createTransport({
"host": process.env.SMTP_HOST,
"port": process.env.SMTP_PORT,
"secure": process.env.SMTP_SECURE,
"auth": {
"user": process.env.SMTP_USER,
"pass": process.env.SMTP_PASS
},
"tls": {
"rejectUnauthorized": false
}
});
/**
* Helper function for reading a file as text. This function promisifies the fs.readFile
* function.
* @private
* @param fname {String} - The filename of the email template file
* @return {Promise} A promise which returns contents of the file as a string.
*/
function readFile(fname)
{
return new Promise((resolve, reject) =>
{
fs.readFile(path.resolve(fname), 'UTF-8', (err, data) =>
{
if (err) reject(err);
else resolve(data);
});
});
}
/**
* A helper function that renders a template string based on a given context, where
* the context is a JSON object describing what to replace.
* @private
* @param str {String} - The initial template string
* @param context {Object} - JSON object with properties available in the template
* @param base {String} - Base name to append to all the properties
* @return {String} The transformed template string
*/
function render(str, context, base)
{
if (typeof (context) !== "object")
{
let regex = base.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
regex = `\{\{\\s*${ regex }\\s*\}\}`;
return str.replace(new RegExp(regex, 'g'), context);
}
for (let prop in context)
{
if (context.hasOwnProperty(prop))
str = render(str, context[prop], base != null ? `${base}.${prop}` : prop);
}
return str;
}
async function getTemplate(name, context)
{
let template = await readFile(name);
return render(template, context);
}
module.exports.NewTicketEvent = {
"template": "mailtemplates/newTicket.html",
"subject": "New ticket is raised on Miracle Help Desk"
};
module.exports.TicketAssignedEvent = {
"template": "mailtemplates/ticketAssigned.html",
"subject": "You have been assigned to a ticket"
};
module.exports.NewReplyEvent = {
"template": "mailtemplates/newReply.html",
"subject": "A new reply has been posted"
};
module.exports.StatusChangedEvent = {
"template": "mailtemplates/statusChanged.html",
"subject": "Your ticket has got a status change"
};
module.exports.notify = async function(user, event, context)
{
let template = await getTemplate(event.template, context);
let email = {
"from": `"Notifications" <${ process.env.SMTP_USER }>`,
"to": user.mail,
"subject": event.subject,
"html": template
};
return await smtp.sendMail(email);
};