Repository: chirag04/mail-listener2 Branch: master Commit: d4e9f904bdaa Files: 6 Total size: 9.9 KB Directory structure: gitextract_2335qcxt/ ├── .gitignore ├── LICENSE ├── index.js ├── package.json ├── readme.md └── test.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules/ ================================================ FILE: LICENSE ================================================ Copyright (c) 2012-2014 Chirag Jain Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: index.js ================================================ var Imap = require('imap'); var util = require('util'); var EventEmitter = require('events').EventEmitter; var MailParser = require("mailparser").MailParser; var fs = require("fs"); var path = require('path'); var async = require('async'); module.exports = MailListener; function MailListener(options) { this.markSeen = !! options.markSeen; this.mailbox = options.mailbox || "INBOX"; if ('string' === typeof options.searchFilter) { this.searchFilter = [options.searchFilter]; } else { this.searchFilter = options.searchFilter || ["UNSEEN"]; } this.fetchUnreadOnStart = !! options.fetchUnreadOnStart; this.mailParserOptions = options.mailParserOptions || {}; if (options.attachments && options.attachmentOptions && options.attachmentOptions.stream) { this.mailParserOptions.streamAttachments = true; } this.attachmentOptions = options.attachmentOptions || {}; this.attachments = options.attachments || false; this.attachmentOptions.directory = (this.attachmentOptions.directory ? this.attachmentOptions.directory : ''); this.imap = new Imap({ xoauth2: options.xoauth2, user: options.username, password: options.password, host: options.host, port: options.port, tls: options.tls, tlsOptions: options.tlsOptions || {}, connTimeout: options.connTimeout || null, authTimeout: options.authTimeout || null, debug: options.debug || null }); this.imap.once('ready', imapReady.bind(this)); this.imap.once('close', imapClose.bind(this)); this.imap.on('error', imapError.bind(this)); } util.inherits(MailListener, EventEmitter); MailListener.prototype.start = function() { this.imap.connect(); }; MailListener.prototype.stop = function() { this.imap.end(); }; function imapReady() { var self = this; this.imap.openBox(this.mailbox, false, function(err, mailbox) { if (err) { self.emit('error', err); } else { self.emit('server:connected'); if (self.fetchUnreadOnStart) { parseUnread.call(self); } var listener = imapMail.bind(self); self.imap.on('mail', listener); self.imap.on('update', listener); } }); } function imapClose() { this.emit('server:disconnected'); } function imapError(err) { this.emit('error', err); } function imapMail() { parseUnread.call(this); } function parseUnread() { var self = this; this.imap.search(self.searchFilter, function(err, results) { if (err) { self.emit('error', err); } else if (results.length > 0) { async.each(results, function( result, callback) { var f = self.imap.fetch(result, { bodies: '', markSeen: self.markSeen }); f.on('message', function(msg, seqno) { var parser = new MailParser(self.mailParserOptions); var attributes = null; var emlbuffer = new Buffer(''); parser.on("end", function(mail) { mail.eml = emlbuffer.toString('utf-8'); if (!self.mailParserOptions.streamAttachments && mail.attachments && self.attachments) { async.each(mail.attachments, function( attachment, callback) { fs.writeFile(self.attachmentOptions.directory + attachment.generatedFileName, attachment.content, function(err) { if(err) { self.emit('error', err); callback() } else { attachment.path = path.resolve(self.attachmentOptions.directory + attachment.generatedFileName); self.emit('attachment', attachment); callback() } }); }, function(err){ self.emit('mail', mail, seqno, attributes); callback() }); } else { self.emit('mail',mail,seqno,attributes); } }); parser.on("attachment", function (attachment) { self.emit('attachment', attachment); }); msg.on('body', function(stream, info) { stream.on('data', function(chunk) { emlbuffer = Buffer.concat([emlbuffer, chunk]); }); stream.once('end', function() { parser.write(emlbuffer); parser.end(); }); }); msg.on('attributes', function(attrs) { attributes = attrs; }); }); f.once('error', function(err) { self.emit('error', err); }); }, function(err){ if( err ) { self.emit('error', err); } }); } }); } ================================================ FILE: package.json ================================================ { "name": "mail-listener2", "version": "0.3.1", "description": "Mail listener library for node.js. Get notification when new email arrived.", "dependencies": { "imap": "~0.8.14", "mailparser": "~0.4.6", "async": "^0.9.0" }, "repository": { "type": "git", "url": "git://github.com/chirag04/mail-listener2.git" }, "homepage": "https://github.com/chirag04/mail-listener2", "keywords": [ "mail", "job", "imap", "mail listener", "email", "email parser" ], "author": { "name": "Chirag Jain", "email": "jain_chirag04@yahoo.com", "url": "http://chiragjain.tumblr.com" }, "license": "MIT" } ================================================ FILE: readme.md ================================================ # Overview Mail-listener2 library for node.js. Get notification when new email arrived to inbox or when message metadata (e.g. flags) changes externally. Uses IMAP protocol. We are using these libraries: [node-imap](https://github.com/mscdex/node-imap), [mailparser](https://github.com/andris9/mailparser). Heavily inspired by [mail-listener](https://github.com/circuithub/mail-listener). ## Use Install `npm install mail-listener2` JavaScript Code: ```javascript var MailListener = require("mail-listener2"); var mailListener = new MailListener({ username: "imap-username", password: "imap-password", host: "imap-host", port: 993, // imap port tls: true, connTimeout: 10000, // Default by node-imap authTimeout: 5000, // Default by node-imap, debug: console.log, // Or your custom function with only one incoming argument. Default: null tlsOptions: { rejectUnauthorized: false }, mailbox: "INBOX", // mailbox to monitor searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved markSeen: true, // all fetched email willbe marked as seen and not fetched next time fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`, mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib. attachments: true, // download attachments as they are encountered to the project directory attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments }); mailListener.start(); // start listening // stop listening //mailListener.stop(); mailListener.on("server:connected", function(){ console.log("imapConnected"); }); mailListener.on("server:disconnected", function(){ console.log("imapDisconnected"); }); mailListener.on("error", function(err){ console.log(err); }); mailListener.on("mail", function(mail, seqno, attributes){ // do something with mail object including attachments console.log("emailParsed", mail); // mail processing code goes here }); mailListener.on("attachment", function(attachment){ console.log(attachment.path); }); // it's possible to access imap object from node-imap library for performing additional actions. E.x. mailListener.imap.move(:msguids, :mailboxes, function(){}) ``` That's easy! ## Attachments Attachments can be streamed or buffered. This feature is based on how [mailparser](https://github.com/andris9/mailparser#attachments) handles attachments. Setting `attachments: true` will download attachments as buffer objects by default to the project directory. A specific download directory may be specified by setting `attachmentOptions: { directory: "attachments/"}`. Attachments may also be streamed using `attachmentOptions: { stream: "true"}`. The `"attachment"` event will be fired every time an attachment is encountered. Refer to the [mailparser docs](https://github.com/andris9/mailparser#attachment-streaming) for specifics on how to stream attachments. ## License MIT ================================================ FILE: test.js ================================================ var MailListener = require("./"); var mailListener = new MailListener({ username: "xxxx", password: "xxx", host: "imap.gmail.com", port: 993, tls: true, tlsOptions: { rejectUnauthorized: false }, mailbox: "INBOX", markSeen: true, fetchUnreadOnStart: true, attachments: true, attachmentOptions: { directory: "attachments/" } }); mailListener.start(); mailListener.on("server:connected", function(){ console.log("imapConnected"); }); mailListener.on("server:disconnected", function(){ console.log("imapDisconnected"); }); mailListener.on("error", function(err){ console.log(err); }); mailListener.on("mail", function(mail){ console.log(mail); }); mailListener.on("attachment", function(attachment){ console.log(attachment); });