Skip to content

Instantly share code, notes, and snippets.

@gerardo-junior
Created July 31, 2020 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerardo-junior/33b86024ca2cb284e8e248be6c8b1c72 to your computer and use it in GitHub Desktop.
Save gerardo-junior/33b86024ca2cb284e8e248be6c8b1c72 to your computer and use it in GitHub Desktop.
var Imap = require('imap'),
inspect = require('util').inspect;
var imap = new Imap({
user: 'USERNAME',
password: 'PASSWORD',
host: 'IMAP_HOST',
port: 993, // Default port is 993
tls: true,
tlsOptions: {rejectUnauthorized: false}
});
function openInbox(cb) {
// openReadOnly = false
imap.openBox('Inbox', false, cb);
}
imap.once('ready', function () {
openInbox(function (err, box) {
if (err) throw err;
// Search emails having "Some Subject" in their Subject headers
imap.search([['HEADER', 'SUBJECT', 'Some Subject']], function (err, results) {
if (err) throw err;
try {
var f = imap.fetch(results, {bodies: 'TEXT'});
f.on('message', function (msg, seqno) {
msg.on('body', function (stream, info) {
var buffer = '';
stream.on('data', function (chunk) {
buffer += chunk.toString('utf8');
});
stream.once('end', function () {
// Mark the above mails as read
msg.once('attributes', function (attrs) {
let uid = attrs.uid;
imap.addFlags(uid, ['\\Seen'], function (err) {
if (err) {
console.log(err);
} else {
console.log("Marked as read!")
}
});
});
});
});
});
f.once('end', function () {
imap.end();
});
} catch (errorWhileFetching) {
console.log(errorWhileFetching.message);
imap.end();
}
});
});
});
imap.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment