-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
emailer.js
368 lines (315 loc) · 11.2 KB
/
emailer.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
'use strict';
const winston = require('winston');
const nconf = require('nconf');
const Benchpress = require('benchpressjs');
const nodemailer = require('nodemailer');
const wellKnownServices = require('nodemailer/lib/well-known/services');
const { htmlToText } = require('html-to-text');
const url = require('url');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const User = require('./user');
const Plugins = require('./plugins');
const meta = require('./meta');
const translator = require('./translator');
const pubsub = require('./pubsub');
const file = require('./file');
const viewsDir = nconf.get('views_dir');
const Emailer = module.exports;
let prevConfig;
let app;
Emailer.fallbackNotFound = false;
Emailer.transports = {
sendmail: nodemailer.createTransport({
sendmail: true,
newline: 'unix',
}),
smtp: undefined,
};
Emailer.listServices = () => Object.keys(wellKnownServices);
Emailer._defaultPayload = {};
const smtpSettingsChanged = (config) => {
const settings = [
'email:smtpTransport:enabled',
'email:smtpTransport:pool',
'email:smtpTransport:user',
'email:smtpTransport:pass',
'email:smtpTransport:service',
'email:smtpTransport:port',
'email:smtpTransport:host',
'email:smtpTransport:security',
];
// config only has these properties if settings are saved on /admin/settings/email
return settings.some(key => config.hasOwnProperty(key) && config[key] !== prevConfig[key]);
};
const getHostname = () => {
const configUrl = nconf.get('url');
const parsed = url.parse(configUrl);
return parsed.hostname;
};
const buildCustomTemplates = async (config) => {
try {
// If the new config contains any email override values, re-compile those templates
const toBuild = Object
.keys(config)
.filter(prop => prop.startsWith('email:custom:'))
.map(key => key.split(':')[2]);
if (!toBuild.length) {
return;
}
const [templates, allPaths] = await Promise.all([
Emailer.getTemplates(config),
file.walk(viewsDir),
]);
const templatesToBuild = templates.filter(template => toBuild.includes(template.path));
const paths = _.fromPairs(allPaths.map((p) => {
const relative = path.relative(viewsDir, p).replace(/\\/g, '/');
return [relative, p];
}));
await Promise.all(templatesToBuild.map(async (template) => {
const source = await meta.templates.processImports(paths, template.path, template.text);
const compiled = await Benchpress.precompile(source, { filename: template.path });
await fs.promises.writeFile(template.fullpath.replace(/\.tpl$/, '.js'), compiled);
}));
Benchpress.flush();
winston.verbose('[emailer] Built custom email templates');
} catch (err) {
winston.error(`[emailer] Failed to build custom email templates\n${err.stack}`);
}
};
Emailer.getTemplates = async (config) => {
const emailsPath = path.join(viewsDir, 'emails');
let emails = await file.walk(emailsPath);
emails = emails.filter(email => !email.endsWith('.js'));
const templates = await Promise.all(emails.map(async (email) => {
const path = email.replace(emailsPath, '').slice(1).replace('.tpl', '');
const original = await fs.promises.readFile(email, 'utf8');
return {
path: path,
fullpath: email,
text: config[`email:custom:${path}`] || original,
original: original,
isCustom: !!config[`email:custom:${path}`],
};
}));
return templates;
};
Emailer.setupFallbackTransport = (config) => {
winston.verbose('[emailer] Setting up fallback transport');
// Enable SMTP transport if enabled in ACP
if (parseInt(config['email:smtpTransport:enabled'], 10) === 1) {
const smtpOptions = {
name: getHostname(),
pool: config['email:smtpTransport:pool'],
};
if (config['email:smtpTransport:user'] || config['email:smtpTransport:pass']) {
smtpOptions.auth = {
user: config['email:smtpTransport:user'],
pass: config['email:smtpTransport:pass'],
};
}
if (config['email:smtpTransport:service'] === 'nodebb-custom-smtp') {
smtpOptions.port = config['email:smtpTransport:port'];
smtpOptions.host = config['email:smtpTransport:host'];
if (config['email:smtpTransport:security'] === 'NONE') {
smtpOptions.secure = false;
smtpOptions.requireTLS = false;
smtpOptions.ignoreTLS = true;
} else if (config['email:smtpTransport:security'] === 'STARTTLS') {
smtpOptions.secure = false;
smtpOptions.requireTLS = true;
smtpOptions.ignoreTLS = false;
} else {
// meta.config['email:smtpTransport:security'] === 'ENCRYPTED' or undefined
smtpOptions.secure = true;
smtpOptions.requireTLS = true;
smtpOptions.ignoreTLS = false;
}
} else {
smtpOptions.service = String(config['email:smtpTransport:service']);
}
Emailer.transports.smtp = nodemailer.createTransport(smtpOptions);
Emailer.fallbackTransport = Emailer.transports.smtp;
} else {
Emailer.fallbackTransport = Emailer.transports.sendmail;
}
};
Emailer.registerApp = (expressApp) => {
app = expressApp;
let logo = null;
if (meta.config.hasOwnProperty('brand:emailLogo')) {
logo = (!meta.config['brand:emailLogo'].startsWith('http') ? nconf.get('url') : '') + meta.config['brand:emailLogo'];
}
Emailer._defaultPayload = {
url: nconf.get('url'),
site_title: meta.config.title || 'NodeBB',
logo: {
src: logo,
height: meta.config['brand:emailLogo:height'],
width: meta.config['brand:emailLogo:width'],
},
};
Emailer.setupFallbackTransport(meta.config);
buildCustomTemplates(meta.config);
// need to shallow clone the config object
// otherwise prevConfig holds reference to meta.config object,
// which is updated before the pubsub handler is called
prevConfig = { ...meta.config };
pubsub.on('config:update', (config) => {
// config object only contains properties for the specific acp settings page
// not the entire meta.config object
if (config) {
// Update default payload if new logo is uploaded
if (config.hasOwnProperty('brand:emailLogo')) {
Emailer._defaultPayload.logo.src = config['brand:emailLogo'];
}
if (config.hasOwnProperty('brand:emailLogo:height')) {
Emailer._defaultPayload.logo.height = config['brand:emailLogo:height'];
}
if (config.hasOwnProperty('brand:emailLogo:width')) {
Emailer._defaultPayload.logo.width = config['brand:emailLogo:width'];
}
if (smtpSettingsChanged(config)) {
Emailer.setupFallbackTransport(config);
}
buildCustomTemplates(config);
prevConfig = { ...prevConfig, ...config };
}
});
return Emailer;
};
Emailer.send = async (template, uid, params) => {
if (!app) {
throw Error('[emailer] App not ready!');
}
let userData = await User.getUserFields(uid, ['email', 'username', 'email:confirmed', 'banned']);
// 'welcome' and 'verify-email' explicitly used passed-in email address
if (['welcome', 'verify-email'].includes(template)) {
userData.email = params.email;
}
({ template, userData, params } = await Plugins.hooks.fire('filter:email.prepare', { template, uid, userData, params }));
if (!meta.config.sendEmailToBanned && template !== 'banned') {
if (userData.banned) {
winston.warn(`[emailer/send] User ${userData.username} (uid: ${uid}) is banned; not sending email due to system config.`);
return;
}
}
if (!userData || !userData.email) {
if (process.env.NODE_ENV === 'development') {
winston.warn(`uid : ${uid} has no email, not sending "${template}" email.`);
}
return;
}
const allowedTpls = ['verify-email', 'welcome', 'registration_accepted', 'reset', 'reset_notify'];
if (!meta.config.includeUnverifiedEmails && !userData['email:confirmed'] && !allowedTpls.includes(template)) {
if (process.env.NODE_ENV === 'development') {
winston.warn(`uid : ${uid} (${userData.email}) has not confirmed email, not sending "${template}" email.`);
}
return;
}
const userSettings = await User.getSettings(uid);
// Combined passed-in payload with default values
params = { ...Emailer._defaultPayload, ...params };
params.uid = uid;
params.username = userData.username;
params.rtl = await translator.translate('[[language:dir]]', userSettings.userLang) === 'rtl';
const result = await Plugins.hooks.fire('filter:email.cancel', {
cancel: false, // set to true in plugin to cancel sending email
template: template,
params: params,
});
if (result.cancel) {
return;
}
await Emailer.sendToEmail(template, userData.email, userSettings.userLang, params);
};
Emailer.sendToEmail = async (template, email, language, params) => {
const lang = language || meta.config.defaultLang || 'en-GB';
const unsubscribable = ['digest', 'notification'];
// Digests and notifications can be one-click unsubbed
let payload = {
template: template,
uid: params.uid,
};
if (unsubscribable.includes(template)) {
if (template === 'notification') {
payload.type = params.notification.type;
}
payload = jwt.sign(payload, nconf.get('secret'), {
expiresIn: '30d',
});
const unsubUrl = [nconf.get('url'), 'email', 'unsubscribe', payload].join('/');
params.headers = {
'List-Id': `<${[template, params.uid, getHostname()].join('.')}>`,
'List-Unsubscribe': `<${unsubUrl}>`,
'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
...params.headers,
};
params.unsubUrl = unsubUrl;
}
const result = await Plugins.hooks.fire('filter:email.params', {
template: template,
email: email,
language: lang,
params: params,
});
template = result.template;
email = result.email;
params = result.params;
const [html, subject] = await Promise.all([
Emailer.renderAndTranslate(template, params, result.language),
translator.translate(params.subject, result.language),
]);
const data = await Plugins.hooks.fire('filter:email.modify', {
_raw: params,
to: email,
from: meta.config['email:from'] || `no-reply@${getHostname()}`,
from_name: meta.config['email:from_name'] || 'NodeBB',
subject: `[${meta.config.title}] ${_.unescape(subject)}`,
html: html,
plaintext: htmlToText(html, {
tags: { img: { format: 'skip' } },
}),
template: template,
uid: params.uid,
pid: params.pid,
fromUid: params.fromUid,
headers: params.headers,
rtl: params.rtl,
});
const usingFallback = !Plugins.hooks.hasListeners('filter:email.send') &&
!Plugins.hooks.hasListeners('static:email.send');
try {
if (Plugins.hooks.hasListeners('filter:email.send')) {
// Deprecated, remove in v1.19.0
await Plugins.hooks.fire('filter:email.send', data);
} else if (Plugins.hooks.hasListeners('static:email.send')) {
await Plugins.hooks.fire('static:email.send', data);
} else {
await Emailer.sendViaFallback(data);
}
} catch (err) {
if (err.code === 'ENOENT' && usingFallback) {
Emailer.fallbackNotFound = true;
throw new Error('[[error:sendmail-not-found]]');
} else {
throw err;
}
}
};
Emailer.sendViaFallback = async (data) => {
// Some minor alterations to the data to conform to nodemailer standard
data.text = data.plaintext;
delete data.plaintext;
// NodeMailer uses a combined "from"
data.from = `${data.from_name}<${data.from}>`;
delete data.from_name;
await Emailer.fallbackTransport.sendMail(data);
};
Emailer.renderAndTranslate = async (template, params, lang) => {
const html = await app.renderAsync(`emails/${template}`, params);
return await translator.translate(html, lang);
};
require('./promisify')(Emailer, ['transports']);