Check your imap mailbox with nodejs and receive notifications

Email is still one of the most used communication tools. With nodejs you can
access your IMAP mailbox with relative ease. However, it took me some time
to figure out how to setup a system that keeps connected to the IMAP server and
receives notifications on the mailbox update. Here, I present the simplest
example I could think of. It simply connects to the IMAP server and observes
the inbox.

Here the code
First, install emailjs-imap-client: npm install emailjs-imap-client

And here the code:

var config = [
  'imap.yourserver.com', 993, {
      auth: {
        user: 'your@emailaddress.com',
        pass: 'secretPassword',
      },
      useSecureTransport: true,
      requireTLS: true,
      tls: {rejectUnauthorized: false}}];

  var analyzeEmails = function(path) { //path is for instance inbox
    client.listMailboxes().then((mailboxes) => {
      // console.log(util.inspect(mailboxes));
    })
  }
  var client = new ImapClient(config[0], config[1], config[2]);
  client.logLevel = client.LOG_LEVEL_NONE;
  client.connect().then(() => {
    console.log("connected");
    client.selectMailbox("INBOX").then((inbox) => {
      numberEmails = inbox.exists;
      console.log("# messages: " + numberEmails);
    })
  });
  client.onupdate = function(path, type, value){
    // console.log("Update: path: "+path+", type: "+type+", value: "+value);
    if (type === 'expunge') {
      console.log(util.inspect(value));
      client.listMessages('inbox', value, ['envelope']).then((messages) => {
        messages.forEach((message) => {
          var d = message.envelope;
          console.log("D %s | %s(%s) | %s", d.date, d.from[0].name, d.from[0].address, d.subject)
        });
      });
    } else if (type === 'exists') {
      client.listMessages('inbox', value, ['envelope']).then((messages) => {
        messages.forEach((message) => {
          var d = message.envelope;
          console.log("+ %s | %s(%s) | %s", d.date, d.from[0].name, d.from[0].address, d.subject)
        });
      });
    } else if (type === 'fetch') {
      console.log(util.inspect(value));
    }
  }
  client.onclosemailbox = function(path){
    console.log('Closed: ' + path);
  }
  client.onerror = function(err) {
    console.log(err);
  };

Save the code as, for instance, imap_observer.js and run it with node imap_observer.js.