I am trying to fetch the body of the email and click on the link located inside the the email. I am using node.js Imap. I am able to get the Sender, To, Subject and Date fields but not the body of the email. Here is the code I'm working with:
const P = require("bluebird");
const Imap = require('imap');
const inspect = require('util').inspect
//const MailParser = require(mailparser).MailParser;
var config = {
imap: {
user: 'myGmail@gmail.com',
password: 'mypassword',
host: 'imap.gmail.com',
port: '993',
tls: true
}
};
readInbox = (imap) => {
console.log(`Reading from Inbox...`);
P.promisify(imap.openBox, { context: imap })('INBOX', true)
.then(box => {
var fetch = imap.seq.fetch(box.messages.total + ':*',
{
bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE BODY )',
body: true,
struct: false
});
fetch.on('message', function (msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ')';
msg.on('body', function (stream, info) {
var buffer = ' ', count = 0;
stream.on('data', function (chunk) {
buffer += chunk.toString('utf8');
msg.once('end', function () {
console.log(buffer);
})
});
stream.once('end', function () {
console.log(prefix + 'Parse Header: %s', inspect(Imap.parseHeader(buffer)));
});
});
msg.once('attributes', function (attrs) {
console.log(prefix + 'Attributes %s', inspect(attrs, false, 8));
msg.once('buffer message', function (buffer){
console.log(prefix + buffer, inspect(buffer) )
})
});
msg.once('end', function (attrs) {
console.log(prefix + 'finished');
});
fetch.once('error', function () {
console.log('Fetch error : ' + err);
});
fetch.once('end', function () {
console.log('done fetching the email!')
imap.end();
})
})
}).catch(err => console.error("error", err));
};
const imap = new Imap(config.imap);
imap.once('ready', () => readInbox(imap));
imap.once('error', error => console.error(`Error in IMAP connection:`, error));
imap.once('done', () => console.log('Done.'));
imap.once('end', () => console.log('End.'));
imap.once('close', () => console.log('Close.'));
imap.connect();
via Alberto Mercado
No comments:
Post a Comment