Created
July 31, 2020 20:11
-
-
Save gerardo-junior/33b86024ca2cb284e8e248be6c8b1c72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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