【发布时间】:2019-05-26 19:22:46
【问题描述】:
这是一个模块 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 帐户,也没有检索电子邮件的操作。上面的代码有什么问题?
【问题讨论】:
-
我不知道那个库,但我只是做了一个函数来使用 Nodemailer 通过 Gmail 发送电子邮件,并且我正在使用 Oauth 进行身份验证,另一个选项是允许不安全的连接。我没有看到您在任何地方使用 Oauth,所以您是否授权了与 Gmail 的不安全应用连接?
-
Simon Cadieux,imap定义中有登录信息。据我了解,Nodemailer 不能用于检索 imap 电子邮件。 -
代码看起来没什么问题,所以需要调试一下。它是否能够连接,或者您是否有一个数据包过滤器使连接尝试挂起几分钟?等等。寻找那种不幸。 tcpdump 或 wireshark 可能会很方便。
-
你能添加来自
index.js的代码吗? -
arnt,Styx,我将所有imap代码移到index.js中,并在调试中对其进行了多次调试。我可以看到imap的值被传递到 imap.connect() 中。但是openInbox从未被调用和执行。没有错误抛出。我不太明白imap模块是如何工作的。但在我看来,电子邮件检索(openInbox)从未发生过