Last active
August 13, 2017 19:46
-
-
Save toolness/b7259bdb174891c7081b to your computer and use it in GitHub Desktop.
Outputs a JSON stream of information about all your flagged IMAP messages.
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 _ = 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