- Best Practices
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 is the 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.
Require the node modules and include nunjucks so you can add variables to your HTML email templates.
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 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 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’.
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.
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:
Now you have a controller that will find the users that have selected to receive notifications for a given time, and send them an email when your job-scheduler fires.
Last updated on August 24, 2019