Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
4.4 kB
5
Indexable
Never
const express = require("express");
const multer = require("multer");
const nodemailer = require("nodemailer");
const fs = require("fs");
const Imap = require("imap");
const { simpleParser } = require("mailparser");
const app = express();
const upload = multer({ dest: "uploads/" });

app.use(express.static("public"));

// Configure your SMTP transporter for Gmail
let transporter = nodemailer.createTransport({
  service: "Gmail",
  auth: {
    user: "imfamousofficiel@gmail.com",
    pass: "*****************",
  },
});

// Configure your IMAP client for Gmail
const imap = new Imap({
  user: "imfamousofficiel@gmail.com",
  password: "19672002imfamous@XD",
  host: "imap.gmail.com",
  port: 993,
  tls: true,
});

function openInbox(cb) {
  imap.openBox("INBOX", false, cb);
}

function extractBouncedEmail(parsedEmail) {
  const bounceText = parsedEmail.text;
  const emailRegex = /[\w.-]+@[\w.-]+\.\w+/;
  const match = bounceText.match(emailRegex);
  return match ? match[0] : null;
}

function checkForBounces(successfulEmails) {
  const foundEmails = [];

  imap.once("ready", function () {
    openInbox(function (err, box) {
      if (err) throw err;
      imap.search(
        ["UNSEEN", ["FROM", "mailer-daemon"]],
        function (err, results) {
          if (err || !results || !results.length) {
            imap.end();
            return;
          }

          const fetch = imap.fetch(results, { bodies: "" });
          fetch.on("message", function (msg) {
            msg.on("body", function (stream) {
              simpleParser(stream, async (err, parsed) => {
                if (err) {
                  console.error("Error parsing email:", err);
                  return;
                }
                const bouncedEmail = extractBouncedEmail(parsed);
                if (bouncedEmail) {
                  // Check if the bounced email exists in the successfulEmails array
                  const index = successfulEmails.indexOf(bouncedEmail);
                  if (index !== -1) {
                    // Remove it from the successfulEmails array
                    successfulEmails.splice(index, 1);
                  }
                }
              });
            });
          });

          fetch.on("end", function () {
            // Wait for the fetch to complete before ending the IMAP connection
            imap.end();

            // Add the found emails to the foundEmails array
            foundEmails.push(...successfulEmails);

            // Wait some time for bounce processing to complete before saving the list
            setTimeout(() => {
              fs.writeFileSync(
                "uploads/successful_emails.txt",
                foundEmails.join("\n")
              );
            }, 10000); // Adjust the timeout as needed
          });
        }
      );
    });
  });

  imap.once("error", function (err) {
    console.log(err);
  });

  imap.once("end", function () {
    console.log("Connection ended");
  });

  imap.connect();
}

app.post("/sendEmails", upload.single("file"), async (req, res) => {
  if (!req.file) {
    return res.status(400).send("No file uploaded.");
  }

  let emailList = fs
    .readFileSync(req.file.path, "utf-8")
    .split("\n")
    .filter(Boolean);
  let successfulEmails = [];

  for (const email of emailList) {
    try {
      await transporter.sendMail({
        from: "imfamousofficiel@gmail.com",
        to: email,
        subject: "Email Verification Request",
        text: "Dear Recipient, ...",
      });
      successfulEmails.push(email);
      await new Promise((resolve) => setTimeout(resolve, 1000));
    } catch (error) {
      console.error(`Failed to send to ${email}: ${error}`);
    }
  }

  // Update the list based on the bounce checks
  checkForBounces(successfulEmails);

  // Wait some time for bounce processing to complete before saving the list
  setTimeout(() => {
    fs.writeFileSync(
      "uploads/successful_emails.txt",
      successfulEmails.join("\n")
    );
    res.download("uploads/successful_emails.txt");
  }, 10000); // Adjust the timeout as needed
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Leave a Comment