How to send automated emails through node-cron and nodemailer?

How to send the email to the user on the time given by the user by extracting the time from the database then dynamically sending the time and date to cron schedule. In the Express file structure where to call the cron.schedule method in order to do so that it can be triggered automatically at the particular time without hitting any route from the frontend.

Hi @guptaanshik

Welcome to FCC.

You have presented a very interesting problem which I have also been thinking about. In an attempt to find a solution I came across the following article by one Robert Macauley.

After reading the article I think you can do the following, though I have not attempted it.
I believe for it to work, you need to have a restriction on how frequently a submitted job is supposed to run. Since you are trying to send emails, probably limit it to weekly.

  1. Store the jobs, cron expression and the time when the job is supposed to run next in your database
  2. Schedule a cron job to query the database hourly or daily at a specific time. Each time you query the database, you retrieve all the jobs which are supposed to run within the next one hour and schedule them if you are querying the database hourly. If you are querying the database daily, you retrieve all the jobs which are supposed to run within the next 24 hours.
  3. If a user submits a job which is supposed to run before you next query the database, you will have to schedule it immediately before saving it to the database.
  4. Each time you run a job, make sure to update the database on when the next job is supposed to run.

Regarding where to invoke node-cron.schedule, you can schedule your jobs at server start. It will run for as long as the server is running. For example in your app.js, you can do something like:


const nodeCron = require("node-cron");

const sendEmail = (name, email) => {
    console.log(`Name: ${name}, Email: ${email}`);
}

const jobs = [
    { name: "Jane Doe", email: "jane.doe@gmail.com", cronExpression: "* * * * * *" },
    { name: "John Doe", email: "john.doe@gmail.com", cronExpression: "* * * * * *" },
    { name: "Tim Doe", email: "tim.doe@gmail.com", cronExpression: "* * * * * *" },
    { name: "Jim Doe", email: "jim.doe@gmail.com", cronExpression: "* * * * * *" },
];


for (let i = 0; i < jobs.length; i++) {
    const { cronExpression, name, email } = jobs[i];
    const job = nodeCron.schedule(cronExpression, () => {
        sendEmail(name, email);
    });
    setTimeout(job.stop, 5000)
}

The code above will schedule all the jobs in the array and cancel them after 5 minutes. The jobs for your case must come from a database query. I hope it gives you some ideas on how to solve the problem.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.