如果网站不是 运行,则 nodemailer 不会发送电子邮件

nodemailer is not sending emails if the website is not running

我在我的 MERN 网站上使用 nodemailer 根据日期发送提醒邮件。当网站在浏览器中 运行 时它工作正常,否则,即使日期匹配也不会发送电子邮件!

nodemailer 配置:

const asyncHandler = require("express-async-handler");
const nodemailer = require("nodemailer");

module.exports.sendEmail = asyncHandler(async (req, res, next) => {

  const transporter = nodemailer.createTransport({
    service: //service,
    host: //host,
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: //email,
      pass: //pass,
    },
  });

  transporter.verify((err, success) => {
    if (err) console.error(err);
    console.log("Your config is correct: ");
  });


// mapping through the database to grab the needed data based on the date 

    const mailOptions = {
      from: //email,
      to: //email2,
      subject: "You should recied an email",
      text: `This is a test email!`,
    };

    transporter.sendMail(mailOptions, async (error, info) => {
      if (error) {
        console.log(error);
      } else {
        console.log("Email sent: " + info.response);
      }
      transporter.close();
    });

//end of mapping

  next();
});

server.js :

...
const { sendEmail } = require("./...sendEmail path");
...
app.use(sendEmail);
...

我无法弄清楚问题出在哪里以及如何解决它,所以如果有人能提供帮助,我将不胜感激!

我用 node-cron 作业调度包解决了这个问题。

server.js:

...
const cron = require("node-cron");
const { sendEmail } = require("./...sendEmail path");
...
//app.use(sendEmail); //no need anymore

cron.schedule("*/5 * * * *", () => {
  sendEmail();
  console.log("running a task every five minutes");
});
...

但我不得不从我的 sendEmail 中间件

中删除 next()

如果您想了解更多关于 node-cron 的信息 Click Here