Coder Social home page Coder Social logo

mail-listener's Introduction

Overview

Mail listener library for node.js. Get notification when new email arrived to inbox. Uses IMAP protocol.

We are using these libraries: node-imap, mailparser.

Heavily inspired by this gist.

Use

Install

npm install mail-listener

JavaScript Code:

var MailListener = require("mail-listener");

var mailListener = new MailListener({
  username: "imap-username",
  password: "imap-password",
  host: "imap-host",
  port: 993, // imap port
  secure: true, // use secure connection
  mailbox: "INBOX", // mailbox to monitor
  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`
});

mailListener.start();

mailListener.on("server:connected", function(){
  console.log("imapConnected");
});
  
mailListener.on("mail:arrived", function(id){
  console.log("new mail arrived with id:" + id);
});

mailListener.on("mail:parsed", function(mail){
  // do something with mail object including attachments
  console.log("emailParsed", mail.attachments);
  // mail processing code goes here
});

// it's possible to access imap object from node-imap library for performing additional actions. E.x.
mailListener.imap.move(:msguids, :mailboxes, function(){}) 

CoffeeScript Code:

MailListener = require "mail-listener"

mailListener = new MailListener
  username: "imap-username"
  password: "imap-password"
  host: "imap-host"
  port: 993 # imap port
  secure: true # use secure connection
  mailbox: "INBOX" # mailbox to monitor
  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`


 # start listener. You can stop it calling `stop method`
mailListener.start()

# subscribe to server connected event
mailListener.on "server:connected", ->
  console.log "imap connected"

# subscribe to error events
mailListener.on "error", (err) ->
  console.log "error happened", err

# mail arrived and was parsed by parser 
mailListener.on "mail:parsed", (mail) ->
  # do something with mail object including attachments
  console.log "parsed email with attachment", mail.attachments
  ## mail processing code goes here

## it's possible to access imap object from node-imap library for performing additional actions. E.x.
mailListener.imap.move :msguids, :mailboxes, ->

That's easy!

Contributions

Mail-listener is ready to use in your project. However if you need any feature tell us or fork project and implement it by yourself.

We appreciate feedback!

License

(The MIT License)

Copyright (c) 2011-2013 CircuitHub., https://circuithub.com/

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.

mail-listener's People

Contributors

alz avatar andrewseddon avatar chirag04 avatar podviaznikov avatar reyner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mail-listener's Issues

Error: Hostname/IP doesn't match certificate's altnames

When I try to start mailListener from your example for host: "imap.gmail.com", port: 993 I have next error (node v0.10.4):

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Hostname/IP doesn't match certificate's altnames
    at SecurePair.<anonymous> (tls.js:1292:23)
    at SecurePair.EventEmitter.emit (events.js:92:17)
    at SecurePair.maybeInitFinished (tls.js:896:10)
    at CleartextStream.read [as _read] (tls.js:430:15)
    at CleartextStream.Readable.read (_stream_readable.js:294:10)
    at EncryptedStream.write [as _write] (tls.js:344:25)
    at doWrite (_stream_writable.js:211:10)
    at writeOrBuffer (_stream_writable.js:201:5)
    at EncryptedStream.Writable.write (_stream_writable.js:172:11)
    at write (_stream_readable.js:547:24)

Cannot call method 'on' of undefined

Hi. I've installed mail-listener via npm. When I tried to run example script from README in plain JavaScript it worked fine. But when I send test email into my email box, application crashed and I got error:

28 Jan 19:48:13 - successfully connected to mail server
imap Connected
28 Jan 19:48:14 - successfully opened mail box
28 Jan 19:48:44 - new mail arrived with id 1
28 Jan 19:48:44 - found 1 emails

/home/kuba/testy/mailparser/node_modules/mail-listener/dist/mail.listener.js:65
                    return fetch.on("message", function(msg) {
                                 ^
TypeError: Cannot call method 'on' of undefined
    at ImapConnection.MailListener.start (/home/kuba/testy/mailparser/node_modules/mail-listener/dist/mail.listener.js:65:34)
    at ondata (/home/kuba/testy/mailparser/node_modules/mail-listener/node_modules/imap/lib/imap.js:675:30)
    at CleartextStream.ondata (/home/kuba/testy/mailparser/node_modules/mail-listener/node_modules/imap/lib/imap.js:602:16)
    at CleartextStream.EventEmitter.emit (events.js:96:17)
    at CleartextStream.CryptoStream._push (tls.js:540:12)
    at SecurePair.cycle (tls.js:898:20)
    at EncryptedStream.CryptoStream.write (tls.js:285:13)
    at Socket.ondata (stream.js:38:26)
    at Socket.EventEmitter.emit (events.js:96:17)
    at TCP.onread (net.js:397:14)

imap 0.8 changes

I saw your dependency on imap will automatically include the new minor version (0.8). Just to give you a heads up, there were some API changes which are documented here.

update mail-listener

Hi @podviaznikov,

Quite a few stuff changed in node-imap now.
For eg: fetch has a event emitter style api.

Any plans to update mail-listener to support the latest version of node-imap?

listerner for multiple emails.

Looking for a example to listen for multiple emails. Any heads up?

I need to listen for multiple emails which are going to be configured dynamically and not when the script boots up.

Install is sucessful but example "Cannot find module 'mail-listener'".

I'm on a mac.

I installed mail-listener with npm

thomas@workstation:~/Desktop/gamma/projects/incubaker/open-product2$ npm install mail-listener
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm WARN invalid config registry=""
npm WARN invalid config Must be a full url with 'http://'
npm info trying registry request attempt 1 at 13:32:12
npm http GET https://registry.npmjs.org/mail-listener
npm http 304 https://registry.npmjs.org/mail-listener
npm info install [email protected] into /Users/thomas/Desktop/gamma/projects/incubaker/open-product2
npm info installOne [email protected]
npm WARN engine [email protected]: wanted: {"node":"~0.6.9"} (current: {"node":"v0.8.6","npm":"1.1.61"})
npm info /Users/thomas/Desktop/gamma/projects/incubaker/open-product2/node_modules/mail-listener unbuild
npm info preinstall [email protected]
npm info trying registry request attempt 1 at 13:32:13
npm http GET https://registry.npmjs.org/coffee-script
npm http 304 https://registry.npmjs.org/coffee-script
npm info install [email protected] into /Users/thomas/Desktop/gamma/projects/incubaker/open-product2/node_modules/mail-listener
npm info installOne [email protected]
npm info /Users/thomas/Desktop/gamma/projects/incubaker/open-product2/node_modules/mail-listener/node_modules/coffee-script unbuild
npm info preinstall [email protected]
npm info build /Users/thomas/Desktop/gamma/projects/incubaker/open-product2/node_modules/mail-listener/node_modules/coffee-script
npm info linkStuff [email protected]
npm info install [email protected]
npm info postinstall [email protected]
npm info build /Users/thomas/Desktop/gamma/projects/incubaker/open-product2/node_modules/mail-listener
npm info linkStuff [email protected]
npm info install [email protected]
npm info postinstall [email protected]
[email protected] node_modules/mail-listener
└── [email protected]
npm info ok 

I run the example

thomas@workstation:~/Desktop/gamma/projects/incubaker/open-product2$ node listener.js 

module.js:340
    throw err;
          ^
Error: Cannot find module 'mail-listener'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/Users/thomas/Desktop/gamma/projects/incubaker/open-product2/listener.js:4:16)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)

Change directory into node_modules/

thomas@workstation:~/Desktop/gamma/projects/incubaker/open-product2$ cd ./node_modules/

Shows that mail-listener is there.

thomas@workstation:~/Desktop/gamma/projects/incubaker/open-product2/node_modules$ ls -la
total 0
drwxr-xr-x  13 thomas  staff  442 Nov 20 13:32 .
drwxr-xr-x@ 12 thomas  staff  408 Nov 20 13:26 ..
drwxr-xr-x   4 thomas  staff  136 Nov 15 12:27 .bin
drwxr-xr-x  15 thomas  staff  510 Nov 15 12:27 express
drwxr-xr-x   7 thomas  staff  238 Nov 15 15:34 imap
drwxr-xr-x  15 thomas  staff  510 Nov 15 12:27 jade
drwxr-xr-x  12 thomas  staff  408 Nov 15 16:32 jquery
drwxr-xr-x   7 thomas  staff  238 Nov 15 12:27 jsdom
drwxr-xr-x   8 thomas  staff  272 Nov 20 13:32 mail-listener
drwxr-xr-x  10 thomas  staff  340 Nov 15 15:34 mailparser
drwxr-xr-x  13 thomas  staff  442 Nov 15 12:43 mongolian
drwxr-xr-x  14 thomas  staff  476 Nov 15 12:28 request
drwxr-xr-x  12 thomas  staff  408 Nov 15 16:15 string
thomas@workstation:~/Desktop/gamma/projects/incubaker/open-product2/node_modules$ 

server:Error is never emited.

I think server:error event is never emitted. If yes, then i think is best to remove it from the readme. Also, mail:arrived can be documented.

undefined is not a function

blank app and used the code example. always getting
undefined is not a function

/Applications/MAMP/htdocs/mail/node_modules/mail-listener/dist/mail.listener.js:24
this.imap = new ImapConnection({
^
TypeError: undefined is not a function
at new MailListener (/Applications/MAMP/htdocs/mail/node_modules/mail-listener/dist/mail.listener.js:24:19)
at Object. (/Applications/MAMP/htdocs/mail/app.js:3:20)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)

Can't install using "npm install mail-listener" on Windows 7.

I tried to install mail-listener, but it fails and throws the following error ('node-waf' is not recognized as an internal or external command, operable program or batch file.).

Below is the NPM output.

Thanks

npm install mail-listener
npm http GET https://registry.npmjs.org/mail-listener
npm http 200 https://registry.npmjs.org/mail-listener
npm http GET https://registry.npmjs.org/mail-listener/-/mail-listener-0.0.3.tgz
npm http 200 https://registry.npmjs.org/mail-listener/-/mail-listener-0.0.3.tgz
npm http GET https://registry.npmjs.org/imap
npm http GET https://registry.npmjs.org/mailparser
npm http GET https://registry.npmjs.org/coffee-script
npm http 200 https://registry.npmjs.org/coffee-script
npm http GET https://registry.npmjs.org/coffee-script/-/coffee-script-1.3.1.tgz
npm http 200 https://registry.npmjs.org/coffee-script/-/coffee-script-1.3.1.tgz
npm http 200 https://registry.npmjs.org/imap
npm http GET https://registry.npmjs.org/imap/-/imap-0.3.0.tgz
npm http 200 https://registry.npmjs.org/mailparser
npm http GET https://registry.npmjs.org/mailparser/-/mailparser-0.2.24.tgz
npm http 200 https://registry.npmjs.org/imap/-/imap-0.3.0.tgz
npm http 200 https://registry.npmjs.org/mailparser/-/mailparser-0.2.24.tgz
npm http GET https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/mimelib
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-1.1.3.tgz
npm http 200 https://registry.npmjs.org/mimelib
npm http GET https://registry.npmjs.org/mimelib/-/mimelib-0.1.15.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-1.1.3.tgz
npm http 200 https://registry.npmjs.org/mimelib/-/mimelib-0.1.15.tgz

[email protected] preinstall \nodejs\node_modules\mail-listener\node_modules\mailparser\node_modules\iconv
node-waf configure

'node-waf' is not recognized as an internal or external command,
operable program or batch file.

npm ERR! [email protected] preinstall: node-waf configure
npm ERR! cmd "/c" "node-waf configure" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] preinstall script.
npm ERR! This is most likely a problem with the iconv package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-waf configure
npm ERR! You can get their info via:
npm ERR! npm owner ls iconv
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\Program Files (x86)\nodejs\node.exe" "C:\Program Files (x86)\nodejs\node_modules\npm\bin\npm-cli.js" "install" "mail-listener"
npm ERR! cwd \nodejs
npm ERR! node -v v0.6.15
npm ERR! npm -v 1.1.16
npm ERR! code ELIFECYCLE
npm ERR! message [email protected] preinstall: node-waf configure
npm ERR! message cmd "/c" "node-waf configure" failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! \nodejs\npm-debug.log

Attachment Path

Hi, i try to download the attachment but in the callback don't have a Path.

Thanks

Error: Nothing to fetch

When i set fetchUnreadOnStart: true and try to connect to server without "UNSEEN" emails imap throw error:

/home/alexander/www/new/node_modules/mail-listener/node_modules/imap/lib/imap.js:952
    throw new Error('Nothing to fetch');
          ^
Error: Nothing to fetch
    at ImapConnection._fetch (/home/alexander/www/new/node_modules/mail-listener/node_modules/imap/lib/imap.js:952:11)
    at ImapConnection.fetch (/home/alexander/www/new/node_modules/mail-listener/node_modules/imap/lib/imap.js:945:15)
    at ImapConnection.<anonymous> (/home/alexander/www/new/node_modules/mail-listener/dist/mail.listener.js:83:29)
    at ondata (/home/alexander/www/new/node_modules/mail-listener/node_modules/imap/lib/imap.js:688:30)
    at CleartextStream.ondata (/home/alexander/www/new/node_modules/mail-listener/node_modules/imap/lib/imap.js:615:16)
    at CleartextStream.EventEmitter.emit (events.js:95:17)
    at CleartextStream.<anonymous> (_stream_readable.js:710:14)
    at CleartextStream.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:382:10)
    at _stream_readable.js:375:7

Could you add the error handler in _parseUnreadEmails on this case:
if (Array.isArray(searchResults) && searchResults.length === 0) { ... }
and don't call @imap.fetch function?

Thank you.

Callback when all message retrievals are complete

fetch(< mixed >source, [< object >options, ] < mixed >request, < function >callback) - (void) - Fetches message(s) in the currently open mailbox. source can be a message UID, a message UID range (e.g. '2504:2507' or '' or '2504:'), or an array of message UIDs and/or message UID rang
...
callback has 1 parameter: < Error >err. This is executed when all message retrievals are complete.

There is usage examples here.

Please implement this feature in the options of mail-listener or emit some event from callback function.

Error fetching attachments

I cannot retrive basic attachments from an email. The only ones that can be managed are those who are embeded into the HTML body. All others attachments are not processed because the content-type of those lines from IMAP are declared as plain/text

So next line from mailparser.js will set the flag to false:

textContent = ["text/plain", "text/html"].indexOf(
          this._currentNode.meta.contentType || "") >= 0;
...
...
this._currentNode.attachment = false;

I know it's not a bug related directly with your project but it's so generic that i cannot understand that nobody has ever got it

Stale npm version

I did npm install mail-listener but it didn't have all the changes and broke because the imap API changed. Can you upgrade the npm package? Thanks!

Add IMAP listeners on "close" and "error"

Add please two imap listeners and emits. Something like this:

After @emit "server:connected":

@imap.on "close", (err) =>
    # console.log "IMAP close"
    @emit "imap:close", err

@imap.on "error", (err) =>
    # console.log "IMAP error", err
    @emit "imap:err", err;

I think it may have another predefine handlers by default (stop mailListener, for example, or restart it, or something other). But i need opportunity to set handlers on this events from listeners for mail-listener class like this:

mailListener.on("imap:err", function(){
    console.log("imapError");
});

mailListener.on("imap:close", function(){
    mailListener.restart();
        // or something other code
});

mail listener breaks on receiving new mails

I have node version 0.10.2 on Mac.

I applied the patch below to imap library for connecting to gmail.
mscdex/node-imap#181

But when i receive a new mail, Mail-listener breaks down. Below is the stack trace.

3 Apr 13:47:06 - new mail arrived with id 1

events.js:72
throw er; // Unhandled 'error' event
^
Error
at CleartextStream.write as _write
at doWrite (_stream_writable.js:211:10)
at writeOrBuffer (_stream_writable.js:201:5)
at CleartextStream.Writable.write (_stream_writable.js:172:11)
at ImapConnection._send (/Users/Novanet/Desktop/node-mailer/node_modules/mail-listener/node_modules/imap/lib/imap.js:1546:22)
at ImapConnection._send (/Users/Novanet/Desktop/node-mailer/node_modules/mail-listener/node_modules/imap/lib/imap.js:1537:19)
at ImapConnection._search (/Users/Novanet/Desktop/node-mailer/node_modules/mail-listener/node_modules/imap/lib/imap.js:891:8)
at ImapConnection.search (/Users/Novanet/Desktop/node-mailer/node_modules/mail-listener/node_modules/imap/lib/imap.js:883:8)
at ImapConnection. (/Users/Novanet/Desktop/node-mailer/node_modules/mail-listener/dist/mail.listener.js:52:35)
at ImapConnection.EventEmitter.emit (events.js:95:17)

How should I set "markSeen: true" option correctly?

Problem

I've got the first e-mail and mail-listener fetch it. But mail after fetching stay UNSEEN.
I've got the second e-mail and mail-listener fetch all UNSEEN e-mails in the "INBOX" (by default) mailbox (first and second). And two e-mails (first and second) stay UNSEEN. And so on.

What I need

Incoming e-mails should marks as SEEN on fetch.

Search for solutions

In the imap fetch funcion there is a markSeen option. But it's not work correct, when I just add markSeen: true here:

#5. fetch emails
        @imap.fetch searchResults, 
          headers:
            parse: false
          body: true
          markSeen: true // ← added string!
          cb: (fetch) => 
            ...

It have only next output in console:

16 Apr 10:35:54 - new mail arrived with id 1
16 Apr 10:35:54 - found 1 emails

And incoming e-mail still stay UNSEEN.

Question

Could you help me with this problem? How should I set markSeen: true option in the fetch command options for it correct working? And I think it will be good if there is a posibility to set this option via mail-listener options.

Thank you.

Error: read ECONNRESET. And how can it works by day and night (24/7)?

Sometimes I have that error:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: read ECONNRESET
    at errnoException (net.js:883:11)
    at TCP.onread (net.js:539:19)

I think it occur when my internet connection is down. But when I try to catch it by force disconnect my internet connection mail-listener continues to work correctly and even read incomming emails. But sometimes it throw error.

Mail object incomplete

Hey there, I recognize that this may be an issue with mailparser from @andris9 but I'm hoping you may be able to give me an idea of what I might be doing wrong.

repro
After connecting to my imap account, I fire off an email to myself (tried different senders) and console.log the mail object. The issue arises when I notice that that mail object only contains mail.text, mail.headers, mail.priority, and mail.uid. My understanding is that it should incorporate other properties such as to, from and even subject.

Here is the program I'm running - https://gist.github.com/kylemac/cbb126f9dc25eb853c10

I'm using a gmail imap account, perhaps that is what is wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.