这是一个模块 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
中调用该模块时,我可以在调试中看到代码是从上到下扫描的,扫描的最后一行代码是imap.connect()
然后返回到 index.js
的下一行,没有连接到 gmail 帐户,也没有检索电子邮件的操作。上面的代码有什么问题?
最佳答案
看看这个,这是来自 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 包吗???
关于node.js - 使用 node-imap 检索电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53967482/