0

I'm trying to set-up a cron email job based on a timestamp in a column in a MongoDB database, here is the code I have tried so far...

let CronJob = require('cron').CronJob;
let nodemailer = require('nodemailer');

//user.timestamp is a field in a MongoDB database
new CronJob('* * * * * *', function() {

  if(Date.now().toString() === user.timestamp){

    let message = {
      // Relevant message stuff here
    };

    transporter.sendMail(message, (error, info) => {
      if (error) {
        console.log('Error occurred');
        console.log(error.message);
        return process.exit(1);
      }

      console.log('Message sent successfully!');

      // only needed when using pooled connections
      transporter.close();
    });

  }

});

... However, the email isn't firing out a message. Any ideas on how I can set the cron job to run whenever a UNIX timestamp matches up to the current date/time?

Matt Maclennan
  • 1,266
  • 13
  • 40

1 Answers1

0

The options you're feeding to the sendMail function seem incorrect - you're just giving it the message content. Can you give it a try with the following syntax:

new CronJob('* * * * * *', function() {

    if(Date.now().toString() === user.timestamp){

        let message = {
          // Relevant message stuff here
        };

        let transporter = nodemailer.createTransport({
            host: 'smtp.yoursmtpserver.com',
            port: 587,
            secure: false, // true for port 465, false for other ports
            auth: {
                user: account.user,
                pass: account.pass
            }
        });

        let mailOptions = {
            from: '"Fred Foo " <foo@example.com>', // sender address
            to: 'bar@example.com, baz@example.com', // list of receivers
            subject: 'Hello ✔', // Subject line
            text: message
            html: '<b>Hello world?</b>' // html body
        };

        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message sent: %s', info.messageId);
        });
    });
});
Neekoy
  • 2,325
  • 5
  • 29
  • 48