Schedule Node tasks and Email notifications with SES

May 18th 16

Scheduling an action to fire at a particular point in time is always useful. It allows us to arrange for predefined batch tasks such as fetching from third party services who rate limit access to their API or cleaning up old data. These tasks can be configured as regular occurrences or for one off moments in the future.

Cron is perfect for these repetitive tasks. The package node cron. has a nice API that can integrate these cron tasks into our node apps.

Mail node

Running a Node Cron job with Express

When using with an express app you need to ensure that the cronjob is initialised just before the server is created e.g.:

new CronJob('0 * * * * *', function() {
 // Process
}, null, true, null);

http.createServer(app).listen(app.get('port'), function() {
    console.log(‘Express server on ' + app.get('port'));
});

Nodemailer

Notifications are an amazing way to be updated of crucial information that needs to be actioned. If your server is continually throwing errors you really should know and being emailed is a great universal way to do that. They can be positive too - if you reach a milestone in customers you deserve an congratulatory message.

However, you need to take care in managing how many messages are being sent. It is easy to be overloaded by them. Once you have too many notifications, they lose there importance and there usefulness. It is possible to setup rules in your email reader to filter these notifications however, that is not a perfect solution.

With all of our touchpoint with in-built email notifications emails are a good way of sending updates. We can leverage Amazon Simple Email Service (SES) to provide a straightforward solution to ping us when something important happens.

To setup SES email notifications from a node app we can use nodemailer with ses-transport like so:

Note

You need to verify your email on SES and have to take note the specific server region that you are using.

var nodemailer = require('nodemailer'),
    ses = require('nodemailer-ses-transport');

var transport = nodemailer.createTransport(ses({
        accessKeyId: ‘*********',
        secretAccessKey: ‘*********',
        rateLimit: 1,
        region: ‘region'
    }));

    var options = {
        from: ‘from@email.com',
        to: ’to@email.com',
        subject: ’subject',
        text: “body”,
        attachments : {
            filename: filename,
            path: path
        };
    };

    transport.sendMail(options);

Assemble JavaScript static site generator Cheat Sheet

Next