Write an Email wrapper API in Node.js
I was working on a phonegap application but found the plugins that add the ability to send emails flaky, unreliable and unsupported. I gave up using them and decided to write an API wrapper to do the job for me instead given that the app I was working on already relied on an active internet connection.
You can do this VERY easily in node.js.
Assuming you've already installed node.js and npm the first thin you need to do is create a package.json:
{
"name": "my-api",
"description": "A simple API wrapper for nodemailer to send emails",
"dependencies" : {
"nodemailer": "0.4.x",
"restify": "2.6.x"
}
}
...and a config file:
var config = {}
config.service = 'Gmail'
config.username = '';
config.password = '';
config.sendAddr = 'noreply@myapi.com';
module.exports = config;
Then create your API.
// Include dependencies
var restify = require('restify');
var nodemailer = require('nodemailer');
// Include config
var config = require('./config')
// Setup email config
var smtpTransport = nodemailer.createTransport("SMTP",{
service: config.service,
auth: {
user: config.username,
pass: config.password
}
});
// Create the server and map POST payload to request parameters object
var server = restify.createServer();
server.use(restify.bodyParser({ mapParams: true }));
server.use(
function crossOrigin(req,res,next){
res.header("Access-Control-Allow-Origin", "*"); // the client could be a mobile app so we must allow POSTs from any origin
res.header("Access-Control-Allow-Headers", "X-Requested-With");
return next();
}
);
/**
* API endpoint for sending emails.
*
* @param {string} receipt The email address of the recepient
* @param {string} subject The subject title of the email to send
* @param {string} message The email message
*/
server.post('/email', function create(req, res, next) {
if (!req.params.receipt === undefined ||
req.params.subject === undefined ||
req.params.message === undefined) {
return next(new restify.InvalidArgumentError('receipt, subject, message are required parameters!'));
}
// Send an email to the visitor's welcomer with their details + signature
smtpTransport.sendMail({
from: config.sendAddr,
to: req.params.receipt,
subject: req.params.subject,
html: req.params.message
}, function(error, response){
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response.message);
}
});
res.send(201, req.params);
});
// Start listening on port 8080
server.listen(8080, function() {
console.log('%s listening at %s', server.name, 'http://my-api.app');
});
In so long as your app can POST to your API you can send emails! You could do other stuff here as well like store the information being emailed in a database, etc.
For more info see the node.js, restify and nodemailer documentation.
This was my first time using node.js so obviously the could can be tidied up quite a lot but it just goes to show how easy this is!
Written by Steffan Harries
Related protips
1 Response
Thanks you very much, interesting