Nodemailer 不会在退出时发送邮件

Nodemailer Won't Mail On Exit

在我的脚本中,我想使用 Nodemailer 发送一封电子邮件,其中包含有关脚本 运行 的数据。脚本中间使用了相同的 transporter,我成功发送了电子邮件。但是,退出事件处理程序中的相同代码根本不执行任何操作。没有电子邮件,没有 "Report Sent!" 输出到控制台,尽管我确实得到了 mailOption 变量的输出到控制台。假设异步操作在退出之前可能没有完成,我添加了一个临时延迟步骤来验证这一点。仍然没有生成电子邮件。我做错了什么吗?

function exitHandler(er) {
  end = moment().utc();

  // report template
  var tplPath = path.resolve('report.html');
  var juiceFileDeAsync = deasync(juice.juiceFile);
  var tpl = juiceFileDeAsync(tplPath, { webResources: {images: false} });
  var email = nunjucks.renderString(tpl, {
    startDate: start.format("MMMM Do YYYY, h:mm:ss a"),
    duration: end.diff(start,'seconds'),
    report: sentEmails,
    warns: warns,
    errors: errors
  });
  // email report
  mailOptions.to = '<valid email>';
  mailOptions.html = email;
  transporter.sendMail(mailOptions, function(error, info) {
    console.log('Report sent!', error, info);
  });
  console.log(mailOptions);
  if (er) {
    console.log(er);
  }

  var e = new Date().getTime() + (10 * 1000);
  while (new Date().getTime() <= e) {
    ;
  }

}

// do something when app is closing
process.on('exit', exitHandler);
process.on('uncaughtException', exitHandler);

https://nodejs.org/api/process.html 查看事件:退出文档:

process.on('exit', function(code) {
    // do *NOT* do this
    setTimeout(function() {
        console.log('This will not run');
    }, 0);
    console.log('About to exit with code:', code);
});

once all exit listeners have finished running the process will exit. Therefore you must only perform synchronous operations in this handler.