Skip to content

Instantly share code, notes, and snippets.

@dgouldin
Last active August 29, 2015 14:19
Show Gist options
  • Save dgouldin/8f023120b00e5e9e0250 to your computer and use it in GitHub Desktop.
Save dgouldin/8f023120b00e5e9e0250 to your computer and use it in GitHub Desktop.
Gmail IDLE test
require("babel/register");
var Imap = require('imap');
var imap = new Imap({
user: process.env.USERNAME,
password: process.env.PASSWORD,
host: 'imap.gmail.com',
port: 993,
tls: true
});
var skipResult = true; // skip the first mail result
var onMessage = (msg, seqno) => {
var prefix = '(#' + seqno + ')';
var body = '';
var attrs;
msg.on('body', (stream, info) => {
stream.on('data', chunk => body += chunk);
});
msg.once('attributes', a => attrs = a);
msg.once('end', () => {
console.log(prefix, 'Finished');
console.log(prefix, 'Body', body);
console.log(prefix, 'Attrs', attrs);
// TODO: Take action on the message
imap.addFlags(attrs.uid, ['\Seen'], err => {
if (err) throw err;
});
});
};
imap.once('ready', () => {
imap.on('mail', i => {
console.log(`New mail: ${i}`);
if (skipResult) {
skipResult = false;
return;
}
imap.search(['UNSEEN'], (err, results) => {
if (err) throw err;
console.log('search', results.length);
if (results.length == 0) {
return;
}
imap.fetch(results.slice(-1 * i), {
bodies: ['TEXT', 'HEADER']
}).on('message', onMessage);
});
});
imap.openBox('INBOX', false, (err, box) => {
if (err) throw err;
});
});
imap.once('error', err => console.log(err));
imap.once('end', () => console.log('Connection ended'));
imap.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment