Friday 14 April 2017

Node.js imap connection handling

I need to write a node.js application to keep checking if there is new email from the imap server.

I am trying to write an object handling the imap connection.

var Imap = require('imap'),
    inspect = require('util').inspect;
const fs = require('fs');
var MailParser = require("mailparser").MailParser;  
var Promise = require("bluebird");

function ImapConnection(config){
    if (!(this instanceof ImapConnection))
    return new ImapConnection(config);
    this._imap = new Imap(config);
    this._config = config;
}

ImapConnection.prototype.getImap = function(){
    self = this;
    if(this._imap.state !== 'authenticated'){
        return new Promise(function(resolve,reject){
            self._imap.connect();
            self._imap.once('ready', function(){
                resolve(self._imap);
            });
        });
    }else{
        return new Promise(function(resolve,reject){resolve(this._imap);});
    }
} 

But when I call the object after I called the end() function of the imap object it never connects again and always gives the timeout error:

{ [Error: Timed out while connecting to server] source: 'timeout' }
[connection] Closed
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: Timed out while connecting to server
    at null._onTimeout 
(/home/ctw/Documents/nodejsmail/node_modules/imap/lib/Connection.js:280:15)
    at Timer.listOnTimeout (timers.js:92:15)

Can anyone tell me what's wrong on my code or any other better practice? Thanks.



via ctw

No comments:

Post a Comment