【问题标题】:Getting error while reading outlook mails in Node.js在 Node.js 中阅读 Outlook 邮件时出错
【发布时间】:2022-01-18 19:14:12
【问题描述】:

目标:我正在尝试使用某些过滤器(例如“来自指定用户”、“已读”、“已发送”等)阅读邮件(前景)。使用“IMAP”模块进行解析。我必须阅读邮件并从邮件中下载附件并将其存储在某个位置(最好是本地)。但是我的代码无法连接到邮件服务器。 下面是我的代码,当我运行时会产生'Auth:timeout error'

请让我知道我的代码有什么问题。提前致谢!

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

var myMap;


var imap = new Imap({
  user: "put user id here",
  password: "put your password here",
  host: "outlook.office365.com", //this may differ if you are using some other mail services like yahoo
  port: 993,
  tls: true,
//   connTimeout: 10000, // Default by node-imap 
//   authTimeout: 5000, // Default by node-imap, 
  debug: console.log, // Or your custom function with only one incoming argument. Default: null 
  tlsOptions: true,
  mailbox: "INBOX", // mailbox to monitor 
  searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved 
  markSeen: true, // all fetched email willbe marked as seen and not fetched next time 
  fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`, 
  mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib. 
  attachments: true, // download attachments as they are encountered to the project directory 
  attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments 
});

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

imap.once('ready', function () {
  openInbox(function (err, box) {
    if (err) throw err;
    imap.search(['UNSEEN', ['SUBJECT', 'Give Subject Here']], function (err, results) {
      if (err) throw err;
      var f = imap.fetch(results, { bodies: '1', markSeen: true });
      f.on('message', function (msg, seqno) {
        console.log('Message #%d' + seqno);
        console.log('Message type' + msg.text)
        var prefix = '(#' + seqno + ') ';
        msg.on('body', function (stream, info) {
          stream.on('data', function (chunk) {
            buffer += chunk.toString('utf8');
            console.log("BUFFER" + buffer)

          })
          stream.once('end', function () {
            if (info.which === '1') {
              console.log("BUFFER" + buffer)
            }


          });
          console.log(prefix + 'Body');
          stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt'));
        });
        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(); 

【问题讨论】:

    标签: javascript node.js smtp node-modules imap


    【解决方案1】:

    这并不完全符合您的要求,而是使用 ImapFlow 模块而不是 node-imap 的替代实现,并且我刚刚验证它可以针对 Outlook 工作,看起来像下面的脚本。如果您仍然遇到超时等问题,则可能是防火墙问题。

    const { ImapFlow } = require("imapflow");
    const fs = require("fs").promises;
    
    const client = new ImapFlow({
      host: "outlook.office365.com",
      port: 993,
      secure: true,
      auth: {
        user: "example.user@hotmail.com",
        pass: "secretpass",
      },
      logger: false, // set to true if you want to see IMAP transaction logs
    });
    
    // can't run await in main scope, have to wrap it to an async function
    async function main() {
      // establish the connection and log in
      await client.connect();
    
      // open INBOX folder
      let mailbox = await client.mailboxOpen("INBOX");
    
      // list messages matching provided criteria
      for await (let msg of client.fetch(
        {
          // search query to filter messages
          // https://imapflow.com/global.html#SearchObject
          seen: false,
          subject: "Give Subject Here",
        },
        {
          // attributes to request for
          // https://imapflow.com/global.html#FetchQueryObject
          uid: true,
          flags: true,
          internalDate: true,
          bodyStructure: true,
          // include full message body in the response as well
          source: true,
        }
      )) {
        // extract variables
        let { seq, uid, flags, bodyStructure, internalDate, source } = msg;
    
        console.log(`#${seq} Attributes:`, { seq, uid, flags, bodyStructure, internalDate });
    
        // store message body as an eml file
        await fs.writeFile(`msg-${seq}.eml`, source);
      }
    
      // close the connection
      await client.logout();
    }
    
    main().catch(console.error);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 2017-02-19
      • 2015-03-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多