haraka-plugin-webmailer/index.js

71 lines
2.1 KiB
JavaScript

let fs = require('fs');
let bodyParser = require('body-parser');
let outbound;
let getTemplates = require('./templates');
let errorSender = require('./errorSender');
exports.register = function() {
outbound = this.haraka_require('./outbound');
this.register_hook('init_http', 'initExpress');
}
exports.initExpress = function(next, server) {
server.http.app.use('/webSend', setupRoutes(server.http.express.Router()));
server.http.app.get('/test', (req, res) => res.send("HELLO!"));
next();
};
function setupRoutes(app) {
app.use(bodyParser.json());
app.use(errorSender);
app.post('/template', function(req, res) {
try {
if(!req.body) {
return res.sendError(400, "No body provided.");
}
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);
});
} catch(e) {
res.sendError(500, "Server Error");
throw(e);
}
});
return app;
}