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