2015-06-29 63 views
1

我正在使用IMAP模塊進行Node.js解析IMAP電子郵件的正文。我可以將原始數據作爲原始HTML數據返回給我,但這包括標記和其他不必要的數據。我想的是什麼輸入的文本(去除任何的div,風格等)如何在Node.js IMAP模塊中從body獲取純文本

這裏是代碼我目前正在使用:

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 + '\n\nBody [%s] found, %d total bytes\n\n\n', inspect(info.which), info.size); 
      var buffer = '', count = 0; 
      stream.on('data', function(chunk) { 
      count += chunk.length; 
      buffer += chunk.toString('utf8'); 
      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)); 
      console.log('\n\n\n\n'+buffer.toString()+'\n\n\n\n\n\n'); 
      }); 
     }); 
     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(); 
     }); 
    }); 

有沒有一種方法來解析爲純文本沒有任何標籤或其他HTML信息?

回答

4

有一個節點模塊設計用於: https://www.npmjs.com/package/html-to-text

var htmlToText = require('html-to-text'); 

var text = htmlToText.fromString('<h1>Hello World</h1>', { 
    wordwrap: 130 
}); 
console.log(text); 

它也很好地解析表中的文本。

+0

謝謝!它完美的工作! – feztheforeigner

+0

對於任何未來的讀者,'node-imap'實際上會檢索大多數電子郵件的'text'字段,其中包含純文本版本而沒有任何HTML標記。你可以從'object.text'簡單地訪問它。 https://puu.sh/vOzOL/0fd8a0fe6a.png –

相關問題