nodemailer发送邮件可以,可以不可以收邮件即读取邮箱邮件
发布于 1年前 作者 duni2013 892 次浏览

nodemailer发送邮件可以,可以不可以收邮件即读取邮箱邮件。求高人指点

3 回复

给你一段以前写的收邮件的代码吧,用的是imap协议,就是有点乱,编码默认是gbk,自己可以按需求改改。 我这个功能是收取邮件并保存成以邮件的主题命名是文件。定时调一下就行了。

var util = require('util'),
      ImapConnection = require('imap').ImapConnection;
var MailParser = require("mailparser").MailParser;
var content = require('./com.json');
var fs = require('fs'), fileStream;

var now = new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();

var imap = new ImapConnection({
  username: '[email protected]',
  password: 'XXXXX',
  host: 'imap.163.com',
  port: 993,
  secure: true
});


function die(err) {
  console.log('Uh oh: ' + err);
  process.exit(1);
}

function openInbox(cb) {
  imap.connect(function(err) {
    if (err) die(err);
    imap.openBox('INBOX', false, cb);
  });
}

openInbox(function(err, mailbox) {
  if (err) die(err);
  imap.search([ 'UNSEEN', ['SINCE', 'May 20, 2011'] ], function(err, results) {
    if (err) die(err);
    var fetch = imap.fetch(results, {
      request: {
        headers: false,
        body: 'full'
      }
    });
    fetch.on('message', function(msg) {
      console.log('Got a message with sequence number ' + msg.seqno);
      var name = 'msg-' + msg.seqno + '-raw.eml';
      fileStream = fs.createWriteStream(name);
      var mailparser = new MailParser({defaultCharset:'gbk', streamAttachments: true});
      mailparser.on("end", function(mail_object){
          // console.dir(mail_object);
          console.log("From:", mail_object.from);          //[{address:'[email protected]',name:'Sender Name'}]
          console.log("Subject:", mail_object.subject);
          console.log(mail_object.subject);
          var com = content[mail_object.from];
          fs.rename('./'+name, './'+com+'/'+mail_object.subject+'.eml');
          if(mail_object.attachments){
            for (var i = mail_object.attachments.length - 1; i >= 0; i--) {
              var att = mail_object.attachments[i];
              fs.createWriteStream(att.generatedFileName).end(att.content);
            };
          }
      });
      mailparser.on("attachment", function(attachment){
        var output = fs.createWriteStream(attachment.generatedFileName);
        attachment.stream.pipe(output);
      });
      msg.on('data', function(chunk) {
        fileStream.write(chunk);
        mailparser.write(chunk);
      });
      msg.on('end', function() {
        fileStream.end();
        mailparser.end();
      });
    });
    fetch.on('end', function() {
      console.log('Done fetching all messages!');
      imap.logout();
    });
  });
});

非常感谢,我看一下啊,能否留下你的联系方式,以便沟通,谢谢

可以微博找我,名字一样。@ 我就行~

回到顶部