|
var fs = require('fs') |
|
, parser = require('mailparser') |
|
, imap = require('imap').ImapConnection |
|
, config = JSON.parse(fs.readFileSync("./config.json", "utf-8")) |
|
|
|
var server = new imap({ |
|
username: config.username |
|
, password: config.password |
|
, host: config.host |
|
, port: config.port |
|
}); |
|
|
|
var exitOnErr = function(err) { |
|
console.error(err); |
|
process.exit(1); |
|
} |
|
|
|
|
|
server.connect(function(err) { |
|
if(err) exitOnErr(err); |
|
|
|
// Change 'INBOX' to desired inbox name. |
|
server.openBox('INBOX', false, function(err, box) { |
|
if(err) exitOnErr(err); |
|
console.log("opening inbox..."); |
|
|
|
// The Magic Happens Here! |
|
server.on('mail', function() { |
|
if(err) exitOnErr(err); |
|
console.log("\nNew mail..\n"); |
|
|
|
|
|
// Read docs for search criteria |
|
// https://github.com/mscdex/node-imap#imapconnection-functions |
|
server.search(['NEW'], function(err, results) { |
|
if(err) exitOnErr(err); |
|
|
|
|
|
// Read docs for fetch request information |
|
// https://github.com/mscdex/node-imap#imapconnection-functions |
|
var fetch = server.fetch(results, { request: { headers: false, body: 'full' }}); |
|
|
|
|
|
|
|
fetch.on('message', function(msg) { |
|
console.log("Message No.: " + msg.seqno); |
|
|
|
// Need a new parser per message/mail |
|
// Learned that the hard way. |
|
var parse = new parser.MailParser(); |
|
|
|
|
|
msg.on('data', function(chunk) { |
|
parse.write(chunk); |
|
});//end msg.on.data |
|
|
|
msg.on('end', function() { |
|
parse.end(); |
|
console.log("parsing new mail..."); |
|
});//end msg.on.end |
|
|
|
parse.on('end', function(mailObj) { |
|
|
|
/********************************************\ |
|
|
|
Code for parsing emails goes here. |
|
|
|
\********************************************/ |
|
|
|
console.log('from: ' + mailObj.from[0].address); |
|
console.log('subject: ' + mailObj.subject); |
|
//console.log('body: ' + mailObj.html); // or mailObj.text |
|
});//end parse.on.end |
|
|
|
});//end fetch.on.message |
|
|
|
|
|
fetch.on('end', function() { |
|
console.log("\n\nWaiting for mail..."); |
|
});//end fetch.on.end |
|
|
|
|
|
});//end server.search |
|
});//end server.on.mail |
|
});//end server.openBox |
|
});//end server.connect |