使用node-imap检索电子邮件

时间:2018-12-29 07:07:50

标签: node.js imap node-imap

这里有一个HTML模块,它连接到我的gmail帐户并在日期后下载retrieve_email.js电子邮件。该代码几乎是从UNSEEN模块] 1的示例复制而来的。

[imap

const Imap = require('imap'); const inspect = require('util').inspect; const simpleParser = require('mailparser').simpleParser; const imap = new Imap({ user: 'mygmail@gmail.com', password: 'mypassword', host: 'imap.gmail.com', port: 993, tls: true }); function openInbox(callback) { imap.openBox('INBOX', true, callback); }; async function parse_email(body) { let parsed = simpleParser(body); ............... }; module.exports = function() { imap.once('ready', function() { openInbox(function(err, box) { if (error) throw err; imap.search(['UNSEEN', ['SINCE', 'May 20, 2018']], function(err, results){ if (err) throw err; 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) { if (info.which === 'TEXT') console.log(prefix + 'Body [%s] found, %d total bytes', inspect(info.which), info.size); var buffer = '', count = 0; stream.on('data', function(chunk) { count += chunk.length; buffer += chunk.toString('utf8'); parse_email(buffer); 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)); }); }); 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(); }; 中调用该模块时,我可以在调试中看到从上到下扫描代码,并且扫描的最后一行是index.js,然后返回到下一行。 imap.connect(),没有与gmail帐户的连接,也没有检索电子邮件的操作。上面的代码有什么问题?

UPDATED:index.js之后的调试状态: enter image description here

2 个答案:

答案 0 :(得分:1)

看看这个,这是Google的Gmail API参考。在该页面上,有一个使用Node.js进行连接的示例。

https://developers.google.com/gmail/api/quickstart/nodejs

这是来自同一文档的示例,向您展示了如何使用q参数搜索和检索消息列表:

https://developers.google.com/gmail/api/v1/reference/users/messages/list

P.S。在我的评论中,我只是问您是否确定您已经完成了通过代码访问Gmail帐户所需的所有其他配置工作,这意味着创建应用程序,授权OAuth或在某种情况下授权不安全的应用程序访问,只需查看链接,您可能会发现您缺少某些内容。

您真的需要使用IMAP包吗???

答案 1 :(得分:0)

发现的问题与Avast邮件屏蔽有关,因为中间人拦截了IMAP通信并导致HTTPS失败。此外,IDE调试器会停在某处以保持连接活动但尚未准备好。这是detail of the solution

相关问题