-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodemailer.controller.js
66 lines (64 loc) · 2.71 KB
/
nodemailer.controller.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
'use strict';
const nodemailer = require('nodemailer'),
sg = new WeakMap(),
transporter = new WeakMap(),
private_mail_options = new WeakMap(),
private_methods = {
initialize(mail_options) {
if (mail_options.mail_type === 'nodemailer' && typeof mail_options.nodemailer_options === 'object') {
transporter.set(this, nodemailer.createTransport({
host: mail_options.nodemailer_options.host,
port: mail_options.nodemailer_options.port,
secure: mail_options.nodemailer_options.secure || true,
auth: {
'user': mail_options.nodemailer_options.user,
'pass': mail_options.nodemailer_options.password
}
}));
transporter.get(this).verify((error) => {
if (error) {
throw Error(error);
}
});
} if (mail_options.mail_type === 'sendgrid' && typeof mail_options.sendgrid_options === 'object') {
sg.set(this, require('sendgrid')(mail_options.sendgrid_options.api_key));
} else {
throw Error('Please provide atleast one email configuration');
}
}
};
class MailController {
constructor(mail_options) {
private_mail_options.set(this, mail_options);
private_methods.initialize.call(this, mail_options);
}
sendMail(mailOptions) {
return new Promise((resolve, reject) => {
if (private_mail_options.get(this).mail_type === 'sendgrid') {
const helper = require('sendgrid').mail,
mail = new helper.Mail(new helper.Email(mailOptions.from), mailOptions.subject, new helper.Email(mailOptions.to), new helper.Content('text/html', mailOptions.html)),
requestEmailObj = sg.get(this).emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
sg.get(this).API(requestEmailObj, (error, info) => {
if (error) {
reject(error);
} else {
resolve(info);
}
});
} else if (private_mail_options.get(this).mail_type === 'nodemailer') {
transporter.get(this).sendMail(mailOptions, (error, info) => {
if (error) {
reject(error);
} else {
resolve(info);
}
});
}
});
}
}
module.exports = MailController;