chadxz / imap-simple

Wrapper over node-imap, providing a simpler api for common use cases
MIT License
243 stars 80 forks source link

Not returning anything when retrieve attachments #97

Closed viirenx3 closed 3 years ago

viirenx3 commented 3 years ago

I'm a new bee in programming and find a solution for fetch mail messages with Attachments from Gmail but I'm having an issue with Attachment retrieving some time it works fine but sometimes it struck any solution for this?

I have also need some information about this Attachment Retrieve function that's getPartData() what exactly props this function needs. I know it will be "message" and "part" but message object contain lots of information that need to retrieve Attachment?

let config = { imap: { user: "your@gmail.com", password: "yourpassword", host: "imap.gmail.com", port: 993, tls: true, authTimeout: 3000, }, };

try { await imaps.connect(config).then(async (connection) => { await connection .openBox("INBOX") .then(async () => { try { // Fetch emails from the last 3h var delay = 3 3600 1000; var fetchFrom = new Date(); fetchFrom.setTime(Date.now() - delay); fetchFrom = fetchFrom.toISOString(); var searchCriteria = [["SINCE", fetchFrom]];

      var fetchOptions = {
        bodies: [
          "HEADER",
          "TEXT",
          "HEADER.FIELDS (FROM TO SUBJECT DATE)",
          "",
        ],
        struct: true,
        markSeen: false,
      };

      // retrieve only the headers of the messages
      return connection.search(searchCriteria, fetchOptions);
    } catch (error) {
      console.log("Connection Search", error);
    }
  })
  .then(async (messages) => {
    const getAttachment = async (message, parts) => {
      var mail_attachment = [];
      var attachments = parts.filter(function (part) {
        return (
          part.disposition &&
          part.disposition.type.toUpperCase() === "ATTACHMENT"
        );
      });

      for (let index = 0; index < attachments.length; index++) {
        let part = attachments[index];
        // retrieve the attachments only of the messages with attachments
        await connection
          .getPartData(message, part)
          .then(async (partData) => {
            mail_attachment.push({
              filename: part.disposition.params.filename,
              data: partData,
            });
          });
      }

      return mail_attachment;
    };

    for (let mail_idx1 = 0; mail_idx1 < messages.length; mail_idx1++) {
      let message = messages[mail_idx1];
      var parts = imaps.getParts(message.attributes.struct);

      await getAttachment(message, parts).then(async (result) => {
        messages[mail_idx1]["mail_attachment"] = result;
      });
    }

    return messages;
  })
  .then(function (messages) {
    var mails = messages.map((res) => {
      return {
        part: res.parts.find((part) => part.which === ""),
        attributes: res.attributes,
        mail_attachment: res.mail_attachment,
      };
    });

    mails = [].concat(...mails);

    mails = mails.map((mail) => {
      return new Promise((resolve, reject) => {
        var id = mail.attributes.uid;
        var idHeader = "Imap-Id: " + id + "\r\n";
        var attachments = mail.mail_attachment;
        var mail_size = mail.part.size;

        simpleParser(idHeader + mail.part.body, (error, mail) => {
          if (error) reject(error);
          else {
            resolve({
              queue_id: item.queue_id,
              mail_date_time: mail.date,
              mail_from: mail.from.text,
              mail_to: mail.to.text,
              message_id: mail.messageId,
              mail_body: mail.html,
              subject: mail.subject,
              mail_size,
              attachments,
            });
          }
        });
      });
    });

    return Promise.all(mails).then(
      async (response) => {
        return response;
      },
      (e) => {
        console.log("Mail Response", e.Error ? e.Error : e.message);
        return error;
      }
    );
  })
  .then(function () {
    connection.imap.closeBox(true, (err) => {
      if (err) {
        console.log("FetchMailJob Close Connection", err);
      } else {
        console.log("FetchMailJob Closed Connection");
        connection.end();
      }
    });
    return connection;
  });

}); } catch (e) { console.log("Imap Connect", e.Error ? e.Error : e.message, e); }