Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use node-imap to retrieve emails

Here is a module retrieve_email.js which connects to my gmail account and download the UNSEEN emails after a date. The code is pretty much copied from the example of the [imap module]1.

const Imap = require('imap');
const inspect = require('util').inspect;
const simpleParser = require('mailparser').simpleParser;

const imap = new Imap({
  user: '[email protected]',
  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();
};

When the module is called in index.js, I can see in debug that code is scanned from top to the bottom and the last line of code scanned is imap.connect() and then back to the next line in index.js, with no connection to the gmail account and no action of retrieving the emails. What is wrong with the code above?

UPDATED: status after socket.connect() in debug: enter image description here

like image 967
user938363 Avatar asked Dec 29 '18 07:12

user938363


1 Answers

Have a look at this, this is the Gmail API reference from Google. On that page there is an example of how to connect to it using Node.js.

https://developers.google.com/gmail/api/quickstart/nodejs

And here is an example from the same docs that show you how to search and retrieve message list using the q parameter:

https://developers.google.com/gmail/api/v1/reference/users/messages/list

P.S. In my comment i was just asking you if you were sure that you did all the other configuration stuff needed to access your Gmail account by code, meaning creating the app, authorizing OAuth or in what seemed to be your case authorizing less secure application access, just have a look at the links you might find that you are missing something.

And do you really need to use IMAP package ???

like image 151
Simon Cadieux Avatar answered Sep 24 '22 15:09

Simon Cadieux