0

我正在尝试根据 MongoDB 数据库中列中的时间戳设置 cron 电子邮件作业,这是我迄今为止尝试过的代码...

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();
    });

  }

});

...但是,电子邮件没有发出消息。关于如何将 cron 作业设置为在 UNIX 时间戳与当前日期/时间匹配时运行的任何想法?

4

1 回答 1

0

您提供给 sendMail 函数的选项似乎不正确 - 您只是给它提供了消息内容。您可以使用以下语法尝试一下吗:

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);
        });
    });
});
于 2018-07-11T09:30:14.010 回答