Authored by Timothy Voice, a Brooklyn based software developer and MEAN.JS enthusiast. This post was originally posted on his blog.
Your MEAN app almost always needs to send transactional email to support your overall service such as email confirmations, forgotten passwords, notifications etc. There is a class of apps where email isthe service such as weather apps, newsletter delivery etc. For these services, we need our app to email users automatically at given times and under certain conditions. By combining some great npm modules and hooking into an email service this can be quickly achieved.
There are many choices out there for mail services but I have found Mailgun to have a clean and simple API and the mailgun-js node package makes implementation very straightforward.As for scheduling, the great node-schedule module gives great flexibility, allowing both cron-like and non-cron-like job scheduling. To add scheduled email functionality to your app, follow the steps below.
You will need 4 functions: A mailUsers function to select recipients, mailCreator function to generate the email from a template, a mailSchedulerfunction to trigger the mailing at a certain time, and a mailSender function to send the emails.The Setup
Require the node modules and include nunjucks so you can add variables to your html email templates.Querying the Users
We’re using the mongoose find(x).where(y) query to sift through the users and find those who have selected to receive notifications on the given day and returning a promise.The Mail Creator
The mailCreator takes in an array of users and generates another array that contains the user email address and the html template rendered by nunjucks.The Mailer
The mailSender function will take in a user email, subject and html template for our email and return a promise that when resolved, contains the response from Mailgun’s API; something like ‘Queued. Thank you’.The Scheduler
Here our scheduler function takes in the job we want done and runs it when the rule variable dictates. Here: everyday at 4:38PM. See here for reoccurrence rule making in node-scheduler.Putting it all together
Now all we need to do is call the scheduler function within the node controller, passing in our the users our query returned, mail generator, and mail sender. You can find the whole system in one node controller here.Here is an example scheduled mailing call: