Skip to content

Instantly share code, notes, and snippets.

@toolness
Last active August 13, 2017 19:46
Show Gist options
  • Save toolness/b7259bdb174891c7081b to your computer and use it in GitHub Desktop.
Save toolness/b7259bdb174891c7081b to your computer and use it in GitHub Desktop.
Outputs a JSON stream of information about all your flagged IMAP messages.
var _ = require('underscore');
var Imap = require('imap');
var JSONStream = require('JSONStream');
var USER = process.env.USER;
var PASSWORD = process.env.PASSWORD;
var HOST = process.env.HOST;
var MS_PER_DAY = 1000 * 60 * 60 * 24;
var MAX_AGE = MS_PER_DAY * 90;
var imap = new Imap({
user: USER,
password: PASSWORD,
host: HOST,
port: 993,
tls: true
});
var output = JSONStream.stringify();
function partInfo(struct, info) {
info = info || {};
struct.forEach(function(item) {
if (Array.isArray(item)) return partInfo(item, info);
if (item.partID)
info[item.partID] = item.type + '/' + item.subtype;
});
return info;
}
imap.once('ready', function() {
imap.openBox('INBOX', true, function(err) {
if (err) throw err;
imap.search([
'FLAGGED',
['SENTSINCE', new Date(Date.now() - MAX_AGE)]
], function(err, uids) {
if (err) throw err;
var f = imap.fetch(uids, {
struct: true,
bodies: ['HEADER.FIELDS (FROM SUBJECT DATE)']
});
f.on('message', function(msg, seqno) {
var msgInfo = {};
msg.on('body', function(stream, info) {
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
stream.once('end', function() {
var headers = Imap.parseHeader(buffer);
_.extend(msgInfo, {
subject: headers.subject[0],
from: headers.from[0],
date: headers.date[0]
});
});
});
msg.once('attributes', function(attrs) {
msgInfo.uid = attrs.uid;
msgInfo.parts = partInfo(attrs.struct);
});
msg.once('end', function() {
output.write(msgInfo);
});
});
f.once('end', function() {
imap.end();
});
});
});
});
imap.once('error', function(err) {
throw err;
});
imap.once('end', function() {
output.end();
process.exit(0);
});
imap.connect();
output.pipe(process.stdout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment