Skip to content

Instantly share code, notes, and snippets.

@mduca
Created December 1, 2012 03:52
Show Gist options
  • Save mduca/4180469 to your computer and use it in GitHub Desktop.
Save mduca/4180469 to your computer and use it in GitHub Desktop.
Sit and wait.. for mail

Sit and Wait.. for mail

Used example coffeescript code from bergie's gist. Check it out!

Once configured checkmail.js listens for new mail. Console log will display from, subject, and body then wait for more mail to parse. Thanks to NodeJS's event loop this will happen over and over again.

node-imap and mailparser are used heavily. Make sure these modules are installed.

    npm install imap
            npm install mailparser

Usage

After copying and editing config.json with your email settings run checkmail.js

    cp example.config.json config.json
            node checkmail.js

            `ctrl C` a couple times will end the script.
All feedback is welcome.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment