首页 > 解决方案 > 如果网站未运行,nodemailer 不会发送电子邮件

问题描述

我在我的 MERN 网站上使用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();
});

服务器.js:

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

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

标签: node.jsreactjsmongodbexpressnodemailer

解决方案


我修复了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");
});
...

但我必须next()从我的sendEmail中间件中删除


如果你想了解更多关于 node-cron点击​​这里


推荐阅读