npm install imap
npm install mailparser
var Imap = require(‘imap‘); var inspect = require(‘util‘).inspect; var Mailparser = require(‘mailparser‘).MailParser; var fs = require(‘fs‘); var imap = new Imap({ user: ‘[email protected]‘, password: ‘password‘, host: ‘imap.163.com‘, port: ‘993‘, tls: true }); function openIndex(cb) { imap.openBox(‘INBOX‘,true,cb) ; } imap.once(‘ready‘, function() { openIndex(function(err, box){ //邮件搜索: 2015/7/28以后未读的 imap.search([‘UNSEEN‘, [‘SINCE‘, ‘July 28, 2015‘]], function(err, results){ console.log(results); if(err) console.log( err ); var f = imap.fetch(results, { bodies: ‘‘, struct: true }); f.on(‘message‘, function(msg, seqno){ console.log(‘Message #%d‘, seqno); var prefix = ‘(#‘ + seqno + ‘)‘ ; msg.on(‘body‘, function(stream, info){ console.log(‘INFO WHICH: ‘,info.which); if(info.which === ‘TEXT‘) { console.log(prefix + ‘Body [%s] found, %d total bytes‘,inspect(info.which), info.size) ; } var mailparser = new Mailparser(); stream.pipe(mailparser); mailparser.on(‘end‘,function(mail){ //将mail的内容保存到根目录下的一个html文件里 fs.writeFile(‘msg-‘+seqno+‘-body.html‘,mail.html,function(err){ if(err) throw err; console.log(prefix + ‘saved!‘); }); }); }); 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(); }); }); }); }); imap.once(‘error‘, function(err){ console.log(err) }); imap.once(‘end‘, function(){ console.log(‘Connection ended‘); }); imap.connect();
时间: 2024-10-10 18:08:33