Files
NodeBB/src/emailer.js

352 lines
10 KiB
JavaScript
Raw Normal View History

2017-02-18 01:56:23 -07:00
'use strict';
2014-03-13 00:49:32 -04:00
2019-09-18 17:52:07 -04:00
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');
2019-09-18 17:52:07 -04:00
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');
2020-10-02 11:01:39 -04:00
const viewsDir = nconf.get('views_dir');
2019-09-18 17:52:07 -04:00
const Emailer = module.exports;
let prevConfig;
2020-10-02 11:01:39 -04:00
let app;
Emailer.transports = {
sendmail: nodemailer.createTransport({
sendmail: true,
newline: 'unix',
}),
smtp: undefined,
2016-02-17 20:22:00 +02:00
};
2020-10-02 11:01:39 -04:00
Emailer.listServices = () => Object.keys(wellKnownServices);
Emailer._defaultPayload = {};
2014-11-29 12:12:02 -05:00
2020-10-02 11:01:39 -04:00
const smtpSettingsChanged = (config) => {
const settings = [
'email:smtpTransport:enabled',
'email:smtpTransport:pool',
2020-10-02 11:01:39 -04:00
'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]);
2020-10-02 11:01:39 -04:00
};
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),
]);
2020-10-02 11:01:39 -04:00
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 });
2020-10-02 11:01:39 -04:00
await fs.promises.writeFile(template.fullpath.replace(/\.tpl$/, '.js'), compiled);
}));
Benchpress.flush();
winston.verbose('[emailer] Built custom email templates');
} catch (err) {
2021-02-03 23:59:08 -07:00
winston.error(`[emailer] Failed to build custom email templates\n${err.stack}`);
2020-10-02 11:01:39 -04:00
}
};
2019-09-18 17:52:07 -04:00
2020-10-02 11:01:39 -04:00
Emailer.getTemplates = async (config) => {
2019-09-18 17:52:07 -04:00
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, '').substr(1).replace('.tpl', '');
2020-08-14 00:05:03 -04:00
const original = await fs.promises.readFile(email, 'utf8');
2019-09-18 17:52:07 -04:00
return {
path: path,
fullpath: email,
2021-02-03 23:59:08 -07:00
text: config[`email:custom:${path}`] || original,
2019-09-18 17:52:07 -04:00
original: original,
2021-02-03 23:59:08 -07:00
isCustom: !!config[`email:custom:${path}`],
2019-09-18 17:52:07 -04:00
};
}));
return templates;
};
2020-10-02 11:01:39 -04:00
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) {
2020-10-02 11:01:39 -04:00
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;
2017-05-26 23:55:20 -04:00
} else {
Emailer.fallbackTransport = Emailer.transports.sendmail;
2017-05-26 23:55:20 -04:00
}
};
2020-10-02 11:01:39 -04:00
Emailer.registerApp = (expressApp) => {
app = expressApp;
2020-10-02 11:01:39 -04:00
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);
2015-06-28 21:54:21 -04:00
// 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 };
2020-10-02 11:01:39 -04:00
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 };
}
});
2017-05-26 23:55:20 -04:00
return Emailer;
};
2015-06-28 21:54:21 -04:00
2020-10-02 11:01:39 -04:00
Emailer.send = async (template, uid, params) => {
2017-05-26 23:55:20 -04:00
if (!app) {
throw Error('[emailer] App not ready!');
2017-05-26 23:55:20 -04:00
}
const userData = await User.getUserFields(uid, ['email', 'username', 'email:confirmed']);
2019-09-18 17:52:07 -04:00
if (!userData || !userData.email) {
if (process.env.NODE_ENV === 'development') {
winston.warn(`uid : ${uid} has no email, not sending "${template}" email.`);
}
2019-09-18 17:52:07 -04:00
return;
}
const allowedTpls = ['verify_email', 'welcome', 'registration_accepted'];
if (meta.config.requireEmailConfirmation && !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);
2020-09-04 22:16:38 -04:00
// Combined passed-in payload with default values
params = { ...Emailer._defaultPayload, ...params };
2019-09-18 17:52:07 -04:00
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);
2019-09-18 17:52:07 -04:00
};
2017-05-26 23:55:20 -04:00
2020-10-02 11:01:39 -04:00
Emailer.sendToEmail = async (template, email, language, params) => {
2019-09-18 17:52:07 -04:00
const lang = language || meta.config.defaultLang || 'en-GB';
const unsubscribable = ['digest', 'notification'];
2018-09-25 14:45:43 -04:00
// Digests and notifications can be one-click unsubbed
let payload = {
template: template,
uid: params.uid,
};
if (unsubscribable.includes(template)) {
2019-09-18 17:52:07 -04:00
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 = {
2021-02-03 23:59:08 -07:00
'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', {
2019-09-18 17:52:07 -04:00
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', {
2019-09-18 17:52:07 -04:00
_raw: params,
to: email,
2021-02-03 23:59:08 -07:00
from: meta.config['email:from'] || `no-reply@${getHostname()}`,
2019-09-18 17:52:07 -04:00
from_name: meta.config['email:from_name'] || 'NodeBB',
2021-02-03 23:59:08 -07:00
subject: `[${meta.config.title}] ${_.unescape(subject)}`,
2019-09-18 17:52:07 -04:00
html: html,
plaintext: htmlToText(html, {
tags: { img: { format: 'skip' } },
2019-09-18 17:52:07 -04:00
}),
template: template,
uid: params.uid,
pid: params.pid,
fromUid: params.fromUid,
headers: params.headers,
rtl: params.rtl,
});
try {
if (Plugins.hooks.hasListeners('filter:email.send')) {
// Deprecated, remove in v1.18.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);
2019-09-18 17:52:07 -04:00
} else {
await Emailer.sendViaFallback(data);
}
} catch (err) {
2017-05-26 23:55:20 -04:00
if (err && err.code === 'ENOENT') {
2019-09-18 17:52:07 -04:00
throw new Error('[[error:sendmail-not-found]]');
2015-11-06 14:01:34 -05:00
} else {
2019-09-18 17:52:07 -04:00
throw err;
2015-11-06 14:01:34 -05:00
}
2019-09-18 17:52:07 -04:00
}
2017-05-26 23:55:20 -04:00
};
2015-11-06 14:01:34 -05:00
Emailer.sendViaFallback = async (data) => {
2017-05-26 23:55:20 -04:00
// Some minor alterations to the data to conform to nodemailer standard
data.text = data.plaintext;
delete data.plaintext;
2015-06-28 21:54:21 -04:00
2017-05-26 23:55:20 -04:00
// NodeMailer uses a combined "from"
2021-02-03 23:59:08 -07:00
data.from = `${data.from_name}<${data.from}>`;
2017-05-26 23:55:20 -04:00
delete data.from_name;
2021-02-03 23:59:08 -07:00
winston.verbose(`[emailer] Sending email to uid ${data.uid} (${data.to})`);
await Emailer.fallbackTransport.sendMail(data);
2017-05-26 23:55:20 -04:00
};
2015-11-08 12:28:48 -05:00
2020-10-02 11:01:39 -04:00
Emailer.renderAndTranslate = async (template, params, lang) => {
2021-02-03 23:59:08 -07:00
const html = await app.renderAsync(`emails/${template}`, params);
2019-09-18 17:52:07 -04:00
return await translator.translate(html, lang);
};
2017-05-26 23:55:20 -04:00
2019-07-11 23:43:00 -04:00
require('./promisify')(Emailer, ['transports']);