Search code examples
node.jsimap

How can i handle multiple imap connections in node.js?


how can i monitor multiple email accounts using imap at the same time using node.js?

I have a program to get notifications for single account using node-imap module and parsed emails using mail-parser.

var Imap = require('imap'),
    inspect = require('util').inspect;
var MailParser = require('mailparser').MailParser;
var fs = require('fs');
var imap = new Imap(
{
    user: 'any_email_address',
    password: 'password',
    host: 'imap.host.com',
    port: 993,
    tls: true,
    tlsOptions:
    {
        rejectUnauthorized: false
    }
});

function openInbox(cb)
{
    imap.openBox('INBOX', true, cb);
}

var messages = []

imap.once('ready', function ()
{
    openInbox(function (err, box)
    {
        console.log("open")
        if (err) throw err;
        imap.search(['ALL', []], function (err, results)
        {
            if (err) throw err;
            var f = imap.fetch(results,
            {
                bodies: ''
            });

            f.on('message', function (msg, seqno)
            {
                var mailparser = new MailParser()
                msg.on('body', function (stream, info)
                {
                    stream.pipe(mailparser);
                    mailparser.on("end", function (mail)
                    {
                        fs.writeFile('msg-' + seqno + '-body.html', mail.html, function (err)
                        {
                            if (err) throw err;
                            console.log(seqno + 'saved!');
                        });
                    })
                });
                msg.once('end', function ()
                {
                    console.log(seqno + '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();

Solution

  • You have to create separate connections to monitor multiple accounts.