forked from bgag/keystone-nodemailer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
117 lines (95 loc) · 2.61 KB
/
index.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
var
_ = require('lodash'),
htmlToText = require('html-to-text'),
nodemailer = require('nodemailer');
var transport;
function buildAddress (email, name) {
if (name) {
return name + ' <' + email + '>';
} else {
return email;
}
}
function send (keystone, options, callback) {
// create transport once
if (!transport) {
transport = nodemailer.createTransport(keystone.get('email nodemailer'));
}
var locals = options;
var prepareOptions = [locals];
if (arguments.length === 4 ) {
// we expect locals, options, callback
if (_.isObject(arguments[2])) {
prepareOptions.push(arguments[2]);
}
callback = arguments[3];
} else if (arguments.length === 3 && !_.isFunction(callback)) {
// no callback so we expect locals, options
if (_.isObject(arguments[2])) {
prepareOptions.push(arguments[2]);
}
callback = function(err, info) {// eslint-disable-line no-unused-vars
if (err) console.log(err);
};
} else if (arguments.length === 2) {
// we expect options here and it is pushed already
callback = function(err, info){// eslint-disable-line no-unused-vars
if (err) console.log(err);
};
}
prepareOptions.push(function(err, toSend) {
if (err) {
return callback(err, null);
}
return process.nextTick(function() {
var message = toSend.message;
var attachments = [];
if (message.attachments) {
attachments = message.attachments.map(function (attachment) {
return {
cid: attachment.cid,
filename: attachment.name,
content: attachment.content,
contentType: attachment.type,
encoding: 'base64'
};
});
}
var mail = {
from: buildAddress(message.from_email, message.from_name),
to: message.to.map(function (to) {
return buildAddress(to.email, to.name)
}).join(', '),
subject: message.subject,
html: message.html,
attachments: attachments
};
if (options.sendPlainText) {
if (typeof options.sendPlainText === 'object') {
mail.text = htmlToText.fromString(message.html, options.sendPlainText);
} else {
mail.text = htmlToText.fromString(message.html);
}
}
transport.sendMail(mail, function(error, info) {
if (error) {
callback({
from: 'Email.send',
key: 'send error',
message: 'Nodemailer encountered an error and did not send the emails.',
info: info
});
} else {
callback(null, info);
}
});
});
}.bind(this));
this.prepare.apply(this, prepareOptions);
};
function init (keystone) {
keystone.Email.prototype.send = function (options, callback) {
send.call(this, keystone, options, callback);
};
}
module.exports = init