Read email body with node js imap
Asked Answered
C

3

6

I'm trying to read the body of an e-mail that is retrieved with node js. I'm using this npm module: https://github.com/mscdex/node-imap

And I can get pretty much all the information of the email, except reading the content of the body.

Any ideas?

Thanks,

Chigger answered 20/1, 2014 at 18:42 Comment(0)
D
22

You can use this code to fetch email body and mark it as seen

var Imap = require("imap");
var MailParser = require("mailparser").MailParser;
var Promise = require("bluebird");
Promise.longStackTraces();

var imapConfig = {
    user: 'USERNAME',
    password: 'PASSWORD',
    host: 'HOST',
    port: 993,
    tls: true
};

var imap = new Imap(imapConfig);
Promise.promisifyAll(imap);

imap.once("ready", execute);
imap.once("error", function(err) {
    log.error("Connection error: " + err.stack);
});

imap.connect();

function execute() {
    imap.openBox("INBOX", false, function(err, mailBox) {
        if (err) {
            console.error(err);
            return;
        }
        imap.search(["UNSEEN"], function(err, results) {
            if(!results || !results.length){console.log("No unread mails");imap.end();return;}
            /* mark as seen
            imap.setFlags(results, ['\\Seen'], function(err) {
                if (!err) {
                    console.log("marked as read");
                } else {
                    console.log(JSON.stringify(err, null, 2));
                }
            });*/

            var f = imap.fetch(results, { bodies: "" });
            f.on("message", processMessage);
            f.once("error", function(err) {
                return Promise.reject(err);
            });
            f.once("end", function() {
                console.log("Done fetching all unseen messages.");
                imap.end();
            });
        });
    });
}


function processMessage(msg, seqno) {
    console.log("Processing msg #" + seqno);
    // console.log(msg);

    var parser = new MailParser();
    parser.on("headers", function(headers) {
        console.log("Header: " + JSON.stringify(headers));
    });

    parser.on('data', data => {
        if (data.type === 'text') {
            console.log(seqno);
            console.log(data.text);  /* data.html*/
        }

        // if (data.type === 'attachment') {
        //     console.log(data.filename);
        //     data.content.pipe(process.stdout);
        //     // data.content.on('end', () => data.release());
        // }
     });

    msg.on("body", function(stream) {
        stream.on("data", function(chunk) {
            parser.write(chunk.toString("utf8"));
        });
    });
    msg.once("end", function() {
        // console.log("Finished msg #" + seqno);
        parser.end();
    });
}

hope this code will help you :)

Dordogne answered 21/3, 2017 at 8:32 Comment(6)
Welcome to SO. Please provide some context to your answer. See stackoverflow.com/help/how-to-answerConsuela
does it automatically update when a new mail is sent to that specific email address. Or we need to call a function for that? Does IMAP automatically update the new mails?Cousins
I get the error Connection error: Error: connect ECONNREFUSED 127.0.0.1:143 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14)Dali
How can this example works if i get an error ? ( see question : #59460130 )Dali
set secure to falseDordogne
I'm getting error Connection error: Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed and I get Connection error: Error: Timed out while authenticating with server when tls: false, node -v 12.16.1Amey
C
5

The Body of the message is in the spot where i have console.log("BUFFER", buffer)

I'm using node-imap npm module

 imap.once('ready', function() {
  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)


            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();
      });
    });
});
Chigger answered 20/1, 2014 at 19:19 Comment(1)
I get the error Connection error: Error: connect ECONNREFUSED 127.0.0.1:143 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14)Dali
M
-5

Try:

msg.once('end', function() {
    console.log(buffer);
});
Meliorism answered 31/1, 2015 at 3:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.