Vivek
Vivek

Reputation: 153

How to fetch msg body using node-imap module

I'm using node-imap npm module to fetch the email and i'm getting pretty everything but the content of msg. I used an already provided example on their git, shown below

openInbox(function(err, box) {
    if (err) throw err;
    var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS     (FROM)','TEXT'] });
    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');
                console.log('BUFFER', buffer)  //HEre i am able to view the body
                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();
    });
});

In this example i am able to console out the content of the msg but i am unable to return it as json.

Upvotes: 2

Views: 4641

Answers (1)

Matt Harrison
Matt Harrison

Reputation: 13597

The returned value is a buffer. If you want a string, you can call the toString() method on the buffer. You said you want JSON. If the email body is properly formatted JSON you could also decode it:

var json = JSON.parse(buffer.ToString());

Upvotes: 1

Related Questions