DEV Community

Discussion on: Manage Your're Mail Using IMAP

Collapse
 
mesadhan profile image
Sadhan Sarker

I didn't get your point properly! As far I guess if I not wrong you like to reuse that connection from other classes. I did not try that yet. Let me try first.
Thank you, for such types of motivational comment.

Collapse
 
mesadhan profile image
Sadhan Sarker • Edited

Hope you looking for this.

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

class MailConfig {
    server = new Imap({
        user: 'example@gmail.com',
        password: 'password',
        host: 'imap.gmail.com',
        port: 993,
        tls: true,
        tlsOptions: {
            rejectUnauthorized: false
        },
        authTimeout: 3000
    }).once('error', function (err) {
        console.log('Source Server Error:- ', err);
    });

    constructor() {
        this.server.connect();
    }

    getServer() {
        return this.server;
    }
}

// export & access it from any class

let config = new MailConfig();
let mailServer = config.getServer();

mailServer.once('ready', function () {
    mailServer.openBox('INBOX', true, function (err, box) {
        if (err) throw err;
        console.log('message', 'Source mail server ready');

        let f = mailServer.seq.fetch('1:*', {
            bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
            struct: true
        });
        f.on('message', function (msg, seqno) {
            console.log('Message #%d', seqno);
            let prefix = '(#' + seqno + ') ';
            msg.on('body', function (stream, info) {
                let buffer = '';
                stream.on('data', function (chunk) {
                    buffer += chunk.toString('utf8');
                });
                stream.once('end', function () {
                    console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
                });
            });
        });

    })
});
Thread Thread
 
sripalinm profile image
Sripalinm

Hi Sadhan,

Really Thanks for the kind and quick response, Thanks a lot, That's what I asked.

Thread Thread
 
mesadhan profile image
Sadhan Sarker

Sounds Good! If you think I can help, feel free to knock me.