mscdex / node-imap

An IMAP client module for node.js.
MIT License
2.14k stars 379 forks source link

on 'Mail' is triggering upon open box #759

Open Treverr opened 5 years ago

Treverr commented 5 years ago

I am attempting to implement the following scenario:

  1. Connect to the inbox
  2. Get notified when a NEW email arrvies
  3. Get that emails subject line, mark the message as read

Here is what I have, but the 'mail' is being called upon open.

Here is what I have so far:

var imaps = require('imap'),
    inspect = require('util').inspect;

var imap = new imaps ({
  user: 'ar',
  password: 'abc@123',
  host: '192.168.1.1',
  port: 993,
  tls: true,
  tlsOptions: {
    rejectUnauthorized: false
  },
  authTimeout: 3000
})

function connect() {
  return new Promise(function (resolve, reject) {
    imap.connect();

    imap.on('mail', function(newMail) {
      console.log("New mail", newMail);
      getCodeFromMail();
    })
  })
}

imap.once('ready', function() {
  imap.openBox('INBOX', false, function(err, box) {
    console.log("Success to inbox", box.messages.total);
  });
});

function getCodeFromMail() {
  return new Promise(function (resolve, reject) {
    var fetch = imap.seq.fetch('1:1', {
      bodies: 'HEADER.FIELDS (SUBJECT)'
    })
    fetch.on('message', function(msg, seqno) {
      msg.on('body', function(stream, info) {
        var buffer = '';
        stream.on('data', function(chunk) {
          buffer += chunk.toString('utf8');
        })
        stream.once('end', function() {
          console.log('Parsed Header: ', inspect(imaps.parseHeader(buffer))));
        })
      })
    })
  })
}

connect();

As soon as I run this it outputs:

New mail 1 Success to inbox 1 before a message even arrives (though there is an unread email in the inbox)

mscdex commented 5 years ago

Can you set debug: console.log in your connection config object and post the resulting output (censoring sensitive information first)?

Treverr commented 5 years ago

I found this PR https://github.com/mscdex/node-imap/pull/439 that looks to resolve the issue.