Search code examples
node.jsreactjsmongodbmern

How to send emails to the registered users automatically by different dates


I am doing a MERN Stack project. In my collection on MongoDB. a single document contains feilds like

  • userName
  • email
  • lastDate

The lastDate property is different for different users. I want to send an email to every user before 3 days of the lastDate automatically. I have no idea how to do that. Please give me guidelines on how to do that. Thank you!


Solution

  • Well, In the past I was looking for a similar solution, I found this, you can use the module named node-cron with nodemailer.

    1. First install it.
    node install node-cron --save
    
    1. Import node-cron and schedule a task
    let cron = require('node-cron');
    
    cron.schedule('* * * * *', () => {
       console.log('running a task every minute');
    });
    

    Note: You can read about several cron schedule patterns here. In the above example, we have scheduled a simple console log in every minute.

    Here is the combined code where I am scheduling the e-mail to send every minute:

      let cron = require('node-cron');
      let nodemailer = require('nodemailer');
    
      // e-mail message options
      let mailOptions = {
            from: '<FROM_EMAIL_ADDRESS>',
            to: '<TO_EMAIL_ADDRESS>',
            subject: 'Email from Node-App: A Test Message!',
            text: 'Some content to send'
       };
    
      // e-mail transport configuration
      let transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
              user: '<FROM_EMAIL_ADDRESS>',
              pass: '<FROM_EMAIL_PASSWORD>'
            }
        });
    
     cron.schedule('* * * * *', () => {
      // Send e-mail
      transporter.sendMail(mailOptions, function(error, info){
            if (error) {
              console.log(error);
            } else {
              console.log('Email sent: ' + info.response);
            }
        });
      });