【问题标题】:nodemailer is not sending emails if the website is not running如果网站未运行,nodemailer 不会发送电子邮件
【发布时间】:2021-12-02 05:18:10
【问题描述】:

我在 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 ScheduleNode CronAgenda 等。
  • @ArifKhan 谢谢!!我使用 Node Corn 并且它有效

标签: node.js reactjs mongodb express nodemailer


【解决方案1】:

我用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-18
    • 2016-12-03
    • 1970-01-01
    • 2017-05-16
    • 2015-05-19
    相关资源
    最近更新 更多