Commit b0f04e75 authored by wu-lee's avatar wu-lee

serve.js - allow beautified notification emails

Created from a handlebars template
parent 3de6ba0e
......@@ -29,7 +29,13 @@ module.exports = {
// REQUIRED field!
to: "Registrations <registrations@example.com>",
subject: "Someone has registered!",
}
},
template: {
// content: 'inline {{ handlebars }} template here'
// file: './handlebars-template.hbs',
// This config file included in template context under 'config' key.
// Also, request under 'request'
},
},
webhook: {
path: '/example-path',
......
......@@ -4,7 +4,7 @@ const toText = require('html2plaintext');
module.exports = (serverConfig = {}) => {
async function send(config, html) {
async function send(config, html, json) {
if (!config.from)
throw new Error("must send with a from: parameter");
if (!config.to)
......@@ -17,6 +17,9 @@ module.exports = (serverConfig = {}) => {
text: toText(html),
attachment: [
{data: html, alternative: true},
{data: JSON.stringify(json),
name: 'form-data.json',
type: 'application/json'},
],
};
......
'use strict';
const express = require('express');
const fs = require('fs');
const handlebars = require('handlebars');
const metalsmith = require('./metalsmith.js');
const email = require('./lib/email.js');
const git = require('./lib/git.js')({});
......@@ -39,6 +40,34 @@ var fileOptions = {
}
};
// Define a function which returns the notification template
const defaultTemplate = (context) => `<pre>${JSON.stringify(context.request.body, null, 2)}</pre>`;
var getTemplate = () => defaultTemplate;
if (config.email.template) {
var content = config.email.template.content;
if (content) {
maillog.info('loading email notification template from config');
const template = handlebars.compile(content);
getTemplate = () => template;
}
else {
const file = config.email.template.file;
maillog.info('email notification template will be loaded from the file: '+file);
getTemplate = () => {
if (file) {
if (fs.existsSync(file)) {
maillog.info('loading email notification template from file: '+file);
content = fs.readFileSync(file, 'utf8');
return handlebars.compile(content);
}
else {
maillog.warn('no such email notification template file: '+file);
return defaultTemplate;
}
}
};
}
}
async function build() {
buildlog.info('starting build...')
......@@ -121,10 +150,16 @@ app.post('/registration', (req, res) => {
submitlog.info('emailing registration notification: ', req.body);
const sendConfig = config.email.registration || {};
send(sendConfig,
`<pre>${JSON.stringify(req.body, null, 2)}</pre>`)
.then(ok, error);
try {
const html = getTemplate()({config, request: req});
send(sendConfig,
html,
req.body)
.then(ok, error);
}
catch(e) {
maillog.error('failed to send notification', e);
}
res.redirect('/home');
});
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment