使用Node.js进行Imap,将Email标记为已读

时间:2014-08-15 11:19:36

标签: node.js email imap

我正在使用带有node.js的Imap,并且每次连接它时,它都会从我提供的数据中获取电子邮件,但不会将它们标记为已读取,因此下一次它会重新显示它们再次。

这是我的代码(这里实现的所有函数都在main.js文件中调用),我可以更改什么来标记我正在读取的电子邮件?

我试图像这里写的那样(how to mark unseen email as seen with node-imap in node.js),但它不起作用..

var Imap = require('imap');
var inspect = require('util').inspect;
var formatter = require('./formatter.js');

var mailError = exports.mailError = [];

var imap = new Imap({
  user: 'aaaaaaaaa@gmail.com',
  password: 'xxxxxxx',
  host: 'imap.gmail.com',
  port: 993,    //Perchè non 143, standard IMAP?
  tls: true,
  markSeen: true
});

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


var onBodyCb = exports.onBodyCb = function(parsedHeaders, body){
    var pos = (body.indexOf("Delivery to the following recipient failed permanently:") + 55);
    var address = body.substr(pos,50);
    var at = address.indexOf("@");
    address = address.substr(0,at+formatter.company.length+formatter.domain.length+2);
    address = address.replace(/ /g,'');
    address = address.replace(/(\r\n|\n|\r)/gm,"");
    console.log("onBodyCB:  "+address+'\n');
    mailError.push(address);    
};

var onFinishedFetching = exports.onFinishedFetching = function(){};

imap.once('ready', function() {
    var fs = require('fs'), fileStream;

    openInbox(function(err, box) {
      if (err) throw err;
      imap.search([ 'UNSEEN', ['SINCE', 'July 10, 2014'] ], function(err, results) {
        if (err) throw err;
        // a questo abbiamo la box a cui possiamo accedere
        var f = imap.fetch(results, { bodies: '' });
        f.on('message', function(msg, seqno) {
          //console.log('Message #%d', seqno);
          var prefix = '(#' + seqno + ') ';
          msg.on('body', function(stream, info) {
            console.log(prefix + 'Body');
            var buffer = '';
             stream.on('data', function(chunk) {
              buffer += chunk.toString('utf8');
            });
            //console.log(buffer);
            stream.once('end', function() {
              //console.log(prefix + 'Parsed header: %s', inspect());
              var header = Imap.parseHeader(buffer);
              exports.onBodyCb(header, buffer);
            });
          });
          //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();
          exports.onFinishedFetching();
        });
      });
    });
});

imap.once('error', function(err) {
  console.log(err);
});

imap.once('end', function() {
  console.log('Connection ended');

});

exports.connect = function(){
    imap.connect();
};

编辑:

我按照建议改变了但它仍然不起作用......

var Imap = require('imap');
var inspect = require('util').inspect;
var formatter = require('./formatter.js');

var mailError = exports.mailError = [];

var imap = new Imap({
  user: 'marco.loco.recruiter@gmail.com',
  password: 'coci2014',
  host: 'imap.gmail.com',
  port: 993,    //Perchè non 143, standard IMAP?
  tls: true,
  markSeen : true,
  markRead : true
});

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


var onBodyCb = exports.onBodyCb = function(parsedHeaders, body){
    var pos = (body.indexOf("Delivery to the following recipient failed permanently:") + 55);
    var address = body.substr(pos,50);
    var at = address.indexOf("@");
    address = address.substr(0,at+formatter.company.length+formatter.domain.length+2);
    address = address.replace(/ /g,'');
    address = address.replace(/(\r\n|\n|\r)/gm,"");
    console.log("onBodyCB:  "+address+'\n');
    mailError.push(address);    
};

var onFinishedFetching = exports.onFinishedFetching = function(){};

imap.once('ready', function() {
    var fs = require('fs'), fileStream;

    openInbox(function(err, box) {
      if (err) throw err;
      imap.search([ 'UNSEEN', ['SINCE', 'July 10, 2014'] ], function(err, results) {
        if (err) throw err;
        // a questo abbiamo la box a cui possiamo accedere
        var f = imap.fetch(results, { bodies: '' });
        f.on('message', function(msg, seqno) {
          //console.log('Message #%d', seqno);
          var prefix = '(#' + seqno + ') ';
          msg.on('body', function(stream, info) {
            //console.log(prefix + 'Body');
            var buffer = '';
             stream.on('data', function(chunk) {
              buffer += chunk.toString('utf8');
            });
            //console.log(buffer);
            stream.once('end', function() {
              //console.log(prefix + 'Parsed header: %s', inspect());
              var header = Imap.parseHeader(buffer);
              exports.onBodyCb(header, buffer);
            });
          });
          //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();
          exports.onFinishedFetching();
        });
      });
    },false);
});

imap.once('error', function(err) {
  console.log(err);
});

imap.once('end', function() {
  console.log('Connection ended');

});

exports.connect = function(){
    imap.connect();
};

3 个答案:

答案 0 :(得分:6)

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 unseen email available"); imap.end();return;}     

            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();
    });
}

{markRead:true}标志有时它不起作用,所以你需要明确调用set imap.setFlags([uuids],['\ Seen'],cb)

答案 1 :(得分:1)

这是一个老问题,但今天我遇到了同样的问题。在imap.seq.fetch调用中,除了body:“”之外还需要markSeen:true。它应该看起来像fetch(results,{bodies:“”,markSeen:true}) -

并且不要忘记以读写模式打开收件箱,正如许多人所说的那样。 imap.openBox('INBOX',false,cb)

答案 2 :(得分:0)

这是一个做同样事情的工作示例。

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

var imap = new Imap({
    user: 'USERNAME',
    password: 'PASSWORD',
    host: 'IMAP_HOST',
    port: 993, // Default port is 993
    tls: true,
    tlsOptions: {rejectUnauthorized: false}
});

function openInbox(cb) {
    // openReadOnly = false
    imap.openBox('Inbox', false, cb);
}

imap.once('ready', function () {
openInbox(function (err, box) {
    if (err) throw err;

    // Search emails having "Some Subject" in their Subject headers
    imap.search([['HEADER', 'SUBJECT', 'Some Subject']], function (err, results) {
        if (err) throw err;

        try {
            var f = imap.fetch(results, {bodies: 'TEXT'});
            f.on('message', function (msg, seqno) {
                msg.on('body', function (stream, info) {
                    var buffer = '';
                    stream.on('data', function (chunk) {
                        buffer += chunk.toString('utf8');
                    });
                    stream.once('end', function () {

                        // Mark the above mails as read
                        msg.once('attributes', function (attrs) {

                            let uid = attrs.uid;
                            imap.addFlags(uid, ['\\Seen'], function (err) {
                                if (err) {
                                    console.log(err);
                                } else {
                                    console.log("Marked as read!")
                                }
                            });

                        });

                    });
                });
            });
            f.once('end', function () {
                imap.end();
            });
        } catch (errorWhileFetching) {
            console.log(errorWhileFetching.message);
            imap.end();
        }

    });
});
});


 imap.connect();