0

In my nodejs project, I want to schedule mail to n number of people on particular weekday(ex. Monday, Tuesday....) in some date range(start date, end date) and also in fix time range(9AM to 7PM) on that date. In this range one person will get only one mail. So want to schedule mail in fix time difference for all people in available time.

For ex. -->> Start date -->> 14-10-2021
             end date -->> 14-11-2021
             start time -->> 9AM
             end time -->> 7PM
             weekDays -->> Monday, Tuesday, Thursday
             number of people --> 500
David Jones
  • 2,879
  • 2
  • 18
  • 23

1 Answers1

0

Ok for this you need a cron expression, So follow this link https://crontab.guru/#*/60_07,19_14-15_*_1,2,4 and you will get the desired expression to accomplish your task and you can even generate multiple different cron expression according to you need, And to send mail to n number of user and you also need users email to send them an email for that follow the below pseudo code.

let cron = require('node-cron');
let nodemailer = require('nodemailer');


cron.schedule('*/60 07,19 14-15 * 1,2,4', () => {
   sendEmailFunction();
});

sendEmailFunction(){
  
   let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: '<FROM_EMAIL_ADDRESS>',
      pass: '<FROM_EMAIL_PASSWORD>'
    }
   });
   
    let mailOptions = {
      from: '<FROM_EMAIL_ADDRESS>',
      subject: 'A Test Message!',
      text: 'Content to send'
    };
    //get all user email id or desired user email id from user collection according to your need
   User.find({}, { email: 1 }).then((emailIds) => {
      emailIds.foreach(emailId => {
         mailOptions.to = emailId;
         
         //send an email
         transporter.sendMail(mailOptions, function(error, info){
           if (error) {
             console.log(error);
           } else {
             console.log('Email sent: ' + info.response);
           }
         });
      })
   }).catch((err) => {
        console.log("error")
   })
}
  • I've edited the cron expression because you've to run to cron for certain period of time and that should not be continuous, So with */60 it will be like 9-19 after 60 mins. – karan ganwani Oct 14 '21 at 06:19
  • if the solution worked for you please up-vote and accept the answer. – karan ganwani Oct 14 '21 at 07:36
  • In this by 07,19 it run only on 7AM and 7PM. but i want 9AM-7PM Scheduling so can we write it like 09-19? By the way i appreciate your effort. but i didn't able to resolve my problem by this. Can you solve this problem by node-schedule rules? – Peeyush Mamodia Oct 14 '21 at 08:38