title: Use node-imap to retrieve emails
body: <p>Here is a module <code>retrieve_email.js</code> which connects to my gmail account and download the <code>UNSEEN</code> emails after a date. The code is pretty much copied from the example of the <code>[imap</code> module]<a href="https://github.com/mscdex/node-imap" rel="noreferrer">1</a>.  </p>
  
  <pre><code>const Imap = require('imap');
  const inspect = require('util').inspect;
  const simpleParser = require('mailparser').simpleParser;
  
  const imap = new Imap({
    user: 'mygmail@gmail.com',
    password: 'mypassword',
    host: 'imap.gmail.com',
    port: 993,
    tls: true
  });
  
  function openInbox(callback) {
      imap.openBox('INBOX', true, callback);
  };
  
  async function parse_email(body) {
    let parsed = simpleParser(body);
    ...............
  };
  
  module.exports = function() {
    imap.once('ready', function() {
      openInbox(function(err, box) {
        if (error) throw err;
  
        imap.search(['UNSEEN', ['SINCE', 'May 20, 2018']], function(err, results){
          if (err) throw err;
          var f = imap.fetch(results, {bodies: ''});
          f.on('message', function(msg, seqno) {
            console.log('Message #%d', seqno);
            var prefix = '(#' + seqno + ') ';
            msg.on('body', function(stream, info) {
              if (info.which === 'TEXT')
                console.log(prefix + 'Body [%s] found, %d total bytes', inspect(info.which), info.size);
                var buffer = '', count = 0;
                stream.on('data', function(chunk) {
                  count += chunk.length;
                  buffer += chunk.toString('utf8');
                  parse_email(buffer);
                  if (info.which === 'TEXT')
                    console.log(prefix + 'Body [%s] (%d/%d)', inspect(info.which), count, info.size);
                });
                stream.once('end', function() {
                  if (info.which !== 'TEXT')
                    console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
                  else
                    console.log(prefix + 'Body [%s] Finished', inspect(info.which));
                });
            });
            msg.once('attributes', function(attrs) {
              console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
            });
            msg.once('end', function() {
              console.log(prefix + 'Finished');
            });
          });
  
          f.once('error', function(err) {
            console.log('Fetch error: ' + err);
          });
  
          f.once('end', function() {
            console.log('Done fetching all messages');
            imap.end();
          });
  
        });
      });
    });
  
    imap.once('error', function(err) {
      console.log(err);
    });
  
    imap.once('end', function() {
      console.log('Connection ended');
    });
  
    imap.connect();
  };
  </code></pre>
  
  <p>When the module is called in <code>index.js</code>, I can see in debug that code is scanned from top to the bottom and the last line of code scanned is <code>imap.connect()</code> and then back to the next line in <code>index.js</code>, with no connection to the gmail account and no action of retrieving the emails. What is wrong with the code above?</p>
  
  <p>UPDATED: status after <code>socket.connect()</code> in debug:
  <a href="https://i.stack.imgur.com/bCyED.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/bCyED.jpg" alt="enter image description here"></a></p>