简体   繁体   English

nodemailer 正在为每个无效的 url 发送 email

[英]nodemailer is sending email for each invalid url

I have created a script in node.js which basically fetch some urls and get their http status codes.我在 node.js 中创建了一个脚本,它基本上获取一些 url 并获取它们的 http 状态代码。 If the http status code are not equal to 200 and I want to send mail using nodemailer.如果 http 状态码不等于 200 并且我想使用 nodemailer 发送邮件。 (In the email I want to also send the url that is down). (在 email 中,我还想发送已关闭的 url)。

Currently if 2 urls are down, nodemailer is sending 2 seperate e-mails.目前,如果 2 个 url 出现故障,nodemailer 将发送 2 封单独的电子邮件。 I only want to send one e-mail which will contain all the invalid urls.我只想发送一封包含所有无效网址的电子邮件。

const request = require("request");
const nodemailer = require("nodemailer");

const urlList = [
  "https://www.google.com",
  "https://www.mongodb.com",
  "https://www.mongoslsdb33.com",
  "https://www.google.comslflalfdkjlsdfj",
];

const transporter = nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 587,
  auth: {
    user: "email",
    pass: "password",
  },
  secure: false,
});

function getStatus(url) {
  return new Promise((resolve, reject) => {
    request(url, function (error, response, body) {
      resolve({
        site: url,
        status:
          !error && response.statusCode == 200
            ? "OK"
            : "Down: " + error.message,
      });
    });
  });
}

let promiseList = urlList.map((url) => getStatus(url));

Promise.all(promiseList).then((resultList) => {
  resultList.forEach((result) => {
    if (result.status.startsWith("Down")) {
      console.log(result);
      const message = {
        from: "from-email",
        to: "to-email",
        subject: "Subject",
        html: `<h1>Following URLs have issues:</h1>
            <p>${result} is down</p>`,
      };

      transporter.sendMail(message, function (err, info) {
        if (err) {
          console.log(err);
        } else {
          console.log(info);
        }
      });
    } else {
      return;
    }
  });
});

This can be a guide to your solution.这可以作为您解决方案的指南。

let promiseList = urlList.map((url) => getStatus(url));

//return a list of only the sites in an array with status of Down
const returnListOfUrls = Promise.all(promiseList).then((resultList) => {
  const listWithDownStatus = resultList.map((result) => result.status.startsWith("Down") && result.site).filter(Boolean)
  return listWithDownStatus
 });

//Once the urls have all been resolved, send mail outside of loop
const runNodeMailer = () => {
  returnListOfUrls.then(res =>{
      const message = {
        from: "from-email",
        to: "to-email",
        subject: "Subject",
        html: `<h1>Following URLs have issues:</h1>
            <p>${res.join(', ')} is down</p>`,
      };
  
  console.log(res, '---', message);
  })
}

runNodeMailer()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM