javascriptnode.jsimapnode-imap

node-imap, mail event not working when multiple email comes


I am using node-imap library to read mail, mail event is not getting triggered 2nd time after initialization.

below is my code

also, its giving Error: read ECONNRESET as error after 1st retrival of the email.

Expecting imap.once('mail', function (x) { } should invoke whenever any new mail arises in the mailbox.

imap.once('mail', function (x) { } is not getting triggered triggered.

This event triggers only once when I run the node.js file, and later it is not getting triggered. Please sugggest.

imap.connect();

imap.once('ready', function () {
    console.log("Imap ready");
    readMail();
});

function readMail() {
    openInbox(function (err, box) {

        imap.once('mail', function (x) {
            console.log("New Mail...", x);
            executeMail(err);
        });
    });
    }
}

Tried below as per the comment but, still doses not worked.

function readMail() {
    openInbox(function (err, box) {

        imap.once('mail', function (x) {
            console.log("New Mail...", x);
            executeMail(err);
            imap.connect();
        });
    });
    }
}

Solution

  • I guess you should use imap.on not imap.once

    imap.on("mail", mail => {
      console.log("New mail arrived 1");
    });
    

    The above code worked for me.