Home > Mobile >  nodemailer is sending email for each invalid url
nodemailer is sending email for each invalid url

Time:01-10

I have created a script in node js which basically fetch some urls and get their http status codes. If the http status code are not equal to 200 and I want to send mail using nodemailer. (In the email I want to also send the url that is down).

Currently if 2 urls are down, nodemailer is sending 2 seperate e-mails. 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;
    }
  });
});

CodePudding user response:

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()
  • Related