这是一个模块retrieve_email.js,它可以连接到我的gmail帐户,并在某个日期后下载UNSEEN电子邮件。代码很大程度上是从[imap模块]1的示例中复制过来的。
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中调用该模块时,我可以在debug中看到从上到下扫描代码,扫描的最后一行代码是imap.connect(),然后返回到index.js中的下一行,没有连接到gmail帐户,也没有检索电子邮件的操作。上面的代码有什么问题?
已更新:调试中的socket.connect()之后的状态:

发布于 2019-01-02 22:32:40
看看这个,这是来自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
附注:在我的评论中,我只是问你,你是否确定你已经完成了通过代码访问你的Gmail账户所需的所有其他配置工作,这意味着创建应用程序,授权OAuth,或者在你看来授权不太安全的应用程序访问,只要看看你可能会发现你遗漏了什么。
你真的需要使用IMAP包吗?
发布于 2019-01-09 10:13:38
发现的问题是作为中间人的Avast邮件屏蔽拦截IMAP流量并导致HTTPS失败。此外,IDE调试器会在某个位置停止,以保持连接处于活动状态,但尚未就绪。这是detail of the solution。
https://stackoverflow.com/questions/53967482
复制相似问题