haraka-plugin-webmailer/index.js

71 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-09-04 07:06:15 +00:00
let fs = require('fs');
let bodyParser = require('body-parser');
2019-09-04 07:47:59 +00:00
let outbound;
2019-09-04 07:06:15 +00:00
2019-09-18 07:28:15 +00:00
let getTemplates = require('./templates');
2019-09-04 07:47:59 +00:00
let errorSender = require('./errorSender');
2019-09-04 07:06:15 +00:00
exports.register = function() {
2019-09-04 07:45:41 +00:00
outbound = this.haraka_require('./outbound');
2019-09-18 07:28:15 +00:00
this.register_hook('init_http', 'initExpress');
}
exports.initExpress = function(next, server) {
2019-09-04 07:06:15 +00:00
server.http.app.use('/webSend', setupRoutes(server.http.express.Router()));
2019-09-04 08:13:17 +00:00
server.http.app.get('/test', (req, res) => res.send("HELLO!"));
2019-09-18 07:28:15 +00:00
next();
};
2019-09-04 07:06:15 +00:00
function setupRoutes(app) {
app.use(bodyParser.json());
app.use(errorSender);
app.post('/template', function(req, res) {
2019-09-18 07:28:15 +00:00
try {
if(!req.body) {
return res.sendError(400, "No body provided.");
2019-09-04 07:06:15 +00:00
}
2019-09-18 07:28:15 +00:00
let {to, from, template, headers} = req.body;
if(!template) {
console.error("Template not found in: ", req.body);
return res.sendError(400, "No template name provided.");
}
return getTemplates().then(function(templates) {
if(!templates[template]) {
return res.sendError(400, `Template not found in ${JSON.stringify(templates)}`);
}
let emailText = `From: ${from}\nTo: ${to}`;
if(headers) {
headers.forEach(function(header) {
emailText += `\n${header}`;
});
}
try {
let {subject, message} = templates[template](req.body);
emailText += `\nSubject: ${subject}\n\n${message}`;
} catch (err) {
console.error("Error building email from template: ", err);
res.sendError(err.httpStatus || 400, err.userMessage || "Error parsing template");
}
outbound.send_email(from, to, emailText, function(code, message) {
console.log(`Queue mail result code: ${code} msg: ${message}`);
res.type("json").send(JSON.stringify({
code,
message
}));
});
}).catch(function(err) {
console.error("Error loading templates:", err);
res.sendError(500, "Server Error");
throw(e);
2019-09-04 07:06:15 +00:00
});
2019-09-18 07:28:15 +00:00
} catch(e) {
2019-09-04 07:06:15 +00:00
res.sendError(500, "Server Error");
2019-09-18 07:28:15 +00:00
throw(e);
}
2019-09-04 07:06:15 +00:00
});
return app;
}