我正在使用 IMAP 库从 gmail 获取电子邮件。我从 Read email body with node js imap 和 https://www.npmjs.com/package/imap得到参考。
我的实现如下:
var Imap = require('imap'),
inspect = require('util').inspect;
var imap = new Imap({
user: '[email protected]',
password: 'xxxxxx',
host: 'imap.gmail.com',
port: 993,
tls: true
});
function openInbox(cb) {
imap.openBox('INBOX', true, cb);
}
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
var f = imap.seq.fetch('1:3', {
bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
struct: true
});
f.on('message', function(msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
stream.once('end', function() {
console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
});
});
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();
注意:用户名/密码是正确的,我已在我的 Gmail 帐户中启用了 IMAP/POP,但仍然收到以下错误:
{ Error: Invalid credentials (Failure)
at Connection._resTagged (xxx/server/node_modules/imap/lib/Connection.js:1502:11)
at Parser.<anonymous> (xxx/server/node_modules/imap/lib/Connection.js:194:10)
at Parser.emit (events.js:193:13)
at Parser._resTagged (xxx/server/node_modules/imap/lib/Parser.js:175:10)
at Parser._parse (xxx/server/node_modules/imap/lib/Parser.js:139:16)
at Parser._tryread (xxx/server/node_modules/imap/lib/Parser.js:82:15)
at TLSSocket.Parser._cbReadable (xxx/server/node_modules/imap/lib/Parser.js:53:12)
at TLSSocket.emit (events.js:193:13)
at emitReadable_ (_stream_readable.js:550:12)
at processTicksAndRejections (internal/process/task_queues.js:81:17)
type: 'no',
textCode: 'AUTHENTICATIONFAILED',
source: 'authentication' }
Connection ended
注意:如果使用 Gmail 帐户,您将需要设置 oAuth:
设置 2 因素身份验证并为您的 Gmail 帐户提供应用程序密码。
在您的 Imap 密码上使用生成的应用程序密码。
为我工作!!
var imapConfig = {
user: `${your mail}`,
password: `${your app passowrd}`,
host: 'imap.gmail.com',
port: 993,
tls: true,
tlsOptions:{rejectUnauthorized:false}
};
对于任何来到此线程的人,如果前面的建议无法帮助解决您的问题,请检查您的脚本以确保您已使用 imap.end() 正确关闭 IMAP 会话。
在上面的示例中,如果“f”生效,imap.end() 就会触发,读取消息,然后“结束”。
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
});
但是,如果没有消息,则脚本中没有其他位置可以处理关闭 IMAP 连接(见下文):
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
imap.connect();
这将使会话保持开放状态。大多数电子邮件系统最多允许 20 个 IMAP 连接。在第 21 次尝试时,即使电子邮件和密码正确,您的脚本也会收到登录失败信息。
IMAP 封锁是暂时的,但可能会持续几个小时。等待一段时间,修复脚本并重试。