Giter Club home page Giter Club logo

nodejs-mail-notifier's Introduction

mail-notifier

Notify your nodejs scripts of incoming imap mail.

introduction

Send mail event for each new email in IMAP INBOX.

synopsis

Start listening new mails :

const notifier = require('mail-notifier');

const imap = {
  user: "yourimapuser",
  password: "yourimappassword",
  host: "imap.host.com",
  port: 993, // imap port
  tls: true,// use secure connection
  tlsOptions: { rejectUnauthorized: false }
};

notifier(imap)
  .on('mail', mail => console.log(mail))
  .start();

Keep it running forever :

const n = notifier(imap);
n.on('end', () => n.start()) // session closed
  .on('mail', mail => console.log(mail.from[0].address, mail.subject))
  .start();

Note: If using a Gmail account, you will need to do two things:

  1. Enable IMAP in your Gmail account settings, which is detailed here.
  2. Authorize "less secure apps", which you is laid out in "Option 2" here.

installation

$ npm install mail-notifier

API

notifier(config, customDbg)

The constructor function creates a new notifier. Parameter provide options needed for imap connection. config :

  • host : imap server host
  • port : imap server port number
  • user : imap user name
  • password : imap password
  • tls : need a tle connection to server
  • tlsOptions : see tls module options
  • markSeen: mark mail as read defaults to true
  • box : mail box read from defaults to 'INBOX'
  • search: search query defaults to ['UNSEEN']
  • connTimeout : Number of milliseconds to wait for a connection to be established. Default: 10000
  • authTimeout : Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000
  • debug: function - if set, the function will be called with one argument, a string containing some debug info. Default: debug output if enabled.

Options from node-imap are also avaliable.

For backward compatibility username is supported.

custommDbg: function - if set, the function will be called with args that contain some mail-notifier debug info. Default: debug output if enabled.

example:

const n = notifier(config, (...args) => {
  const msg = util.format(...args);
  customLogFn(msg);
});

.start()

Start listening for incomming emails.

.stop()

Stop listening and close IMAP connection.

Events

'connected'

Sent when a connection to the server has been made.

'mail'

Sent on incoming new unread email. The parsed Mail is given as first parameter to the event listener.

'error'

Sent when an error occurs with the IMAP connection. The first parameter is the err object.

'end'

Sent when the IMAP connection is closed. This usually happens after a stop method call.

Dependencies

This module relies heavily on node-imap. For more advanced usage, please consider using it directly.

Debugging

Debugging is enabled via the visionmedia/debug module.

To enable debug info add mailnotifier to the DEBUG env variable :

$>DEBUG=mailnotifier node sample/simple-mail-notifier.js

Or to also have imap module debug info :

$>DEBUG=mailnotifier,imap node sample/simple-mail-notifier.js

nodejs-mail-notifier's People

Contributors

amit4got avatar benkaiser avatar fon60 avatar jcreigno avatar lorenzleutgeb avatar mpelekh avatar rd825 avatar royalgamer06 avatar sdejean28 avatar sergeyserg 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

nodejs-mail-notifier's Issues

License?

Is this module released under a license?

Stop Listening

Hello guys,

How could I close the connection after all the emails has been read ?

Imap close doesnt trigger end or error event.

The connection stops without being caught either by "end" or "error" events.

Debug log:

mailnotifier no new mail in INBOX +0ms
imap => 'IDLE IDLE' +0ms
imap <= '+ idling' +71ms
imap [connection] Closed +30s
mailnotifier imap close : errored +1ms

Maybe add
self.emit('end');
in self.imap.once('close') ?

Multiple connection after error or end

After losing a connection (catching 'end' event) I try to reconnect in 30 seconds.
Then the connection established, I get not one but two, three or more connections to imap server.
This happens because of not disconnecting imap after 'end' or 'error'.
I try to stop before each start of notifier but it not works, because notifier checks self.connected, so I removed this check from Notifier.prototype.stop and all works fine for me.
Can you fix this, or give an example how to reconnect to server after losing or some another ending of connection.

Save Raw Data

HI,
Not exactly an issue, but is there a way to save the mail object to eml file.
Basically the raw data from the email object.

Error: connect ECONNREFUSED

Hi,
I'm getting some error recently, it may be connected with imap module, but I'm putting the issue here. I'm getting such message very often while I'm trying to connect to my mailbox:

2013-03-26 1424:31.855 :: 'mail-noitifier' module started
Error: Unable to connect. Reason: Error: connect ECONNREFUSED
    at Socket.errorHandler ([my_project_path]/node_modules/mail-notifier/node_modules/imap/imap.js:139:15)
    at Socket.EventEmitter.emit (events.js:96:17)
    at Socket._destroy.self.errorEmitted (net.js:329:14)
    at process.startup.processNextTick.process._tickCallback (node.js:245:9)
2013-03-26 1424:31.861 :: Error: connect ECONNREFUSED
Error: connect ECONNREFUSED
    at errnoException (net.js:770:11)
    at Object.afterConnect [as oncomplete] (net.js:761:19)

If I'll run the app the second or the third time, everything works fine, but it quite annoying. Any ideas?

TypeError: mime.extension is not a function (Since previous close of issue)

I am running this node module at version "^0.4.1", and I am getting the "Type Error: mime.extension is not a function" issue on some emails. I have reinstalled the dependancy since the fix for Issue #43 was applied, but I am able to reliably recreate the issue when I receive a calendar update/invite from Google Calendar, due to the formatting of their emails.
Any help on this would be greatly appreciated!

Unusual sign-in location detected - how to handle gmail security problems?

I had error leading to page informing about wrong password or username:

But when I logged in by browser using the same username and password I have seen e-mail from google about suspicious login try. More info on page:

https://support.google.com/accounts/answer/2506340?authuser=5&p=sign_in_prevented_csa2&hl=en&authuser=5&visit_id=636746614951011840-2742808467&rd=1

Unusual sign-in location detected
Why you must complete an additional step to sign in

We've detected that you're signing in from a different location than you normally do, and we want to make sure that someone else isn't trying to access your account.
If you can’t provide the information requested

If you can’t verify your identity by providing the information requested, you can also access your account by resetting your password.
How this additional step protects your account

The additional step at sign in is designed to prevent an unauthorized person who does not know you from accessing your account, even if they've obtained your username and password. While this won't necessarily stop people who know you from accessing your account (for that, try 2-step verification), it's an important measure to keep hijackers who have a long list of passwords from doing malicious things with your account, such as creating spam or accessing and deleting valuable data.
Examples of additional steps

Below are some examples of the additional steps we’ll ask you to complete in order to help verify your identity. Depending on the recovery options you’ve previously set up, some examples might not be applicable to your account.

    Answering your secret question
    Verifying your phone number
    Entering a code we’ll send you via SMS or voice message
    Verifying your recovery email address
    Verifying a previous location from where you’ve signed-in

 

If you think you should not have been asked to complete this step or have other comments for us, please send us your feedback.

How to prevent occurring this error?

mail-notifier should try to fetch emails in batches

Reason why I suggest this is that right now, mail-notifier may try to fetch over 1000 emails at a time depending on your search query, which often overloads a server, meaning that the server will return an invalid command, as it's unable to process that many emails.

Considering how the code is written, you could split up the uid list into smaller lists and only fetch the emails assigned those uids and process those before moving onto the next set of uids.

Failing installation 0.2.6

Setting the version to "0.2.5" in package.json and running npm install throws an error: "No compatible version found: [email protected]". I'm currently using Node version 0.10.26 and npm version 3.5.1. Could you maybe give me a heads up?

SyntaxError: Unexpected token .

/var/www/vhosts/chattet.de/maiwell-mail.chattet.de/node_modules/mail-notifier/index.js:117
2|simple-m | Notifier.prototype.dbg = function (...args) {
2|simple-m | ^
2|simple-m | SyntaxError: Unexpected token .
2|simple-m | at Module._compile (module.js:439:25)
2|simple-m | at Object.Module._extensions..js (module.js:474:10)
2|simple-m | at Module.load (module.js:356:32)
2|simple-m | at Function.Module._load (module.js:312:12)
2|simple-m | at Module.require (module.js:364:17)
2|simple-m | at require (module.js:380:17)
2|simple-m | at Object. (/var/www/vhosts/chattet.de/maiwell-mail.chattet.de/node_modules/mail-notifier/sample/simple-mail-notifier.js:1:78)
2|simple-m | at Module._compile (module.js:456:26)
2|simple-m | at Object.Module._extensions..js (module.js:474:10)
2|simple-m | at Module.load (module.js:356:32)

Just times out after a couple seconds

Hi. I use the imap and mailparser modules in my code. I just tried cutting and pasting the sample code in the documentation for mail-notifier. I changed the parameters in the imap variable to use the correct email configuration (same params that work in my existing code). Every time I run this I get:

Error: Connection timed out
at ImapConnection._fnTmrConn (/Users/rich/source/node/notifier/node_modules/mail-notifier/node_modules/imap/imap.js:898:11)
at timer._onTimeout (timers.js:210:16)
at Timer.listOnTimeout as ontimeout

I looked in the node_modules directory and you are using imap 0.3.2. The current version is 0.8.9. That's a pretty big gap. I took a look at your source code and it doesn't look all that hard to upgrade. I don't have time today but I could take a shot at doing the upgrade if you'd like?

Timeout

Is there any way to set a timeout?
Also, I want to disconnect after checking for mails (if there's mail, after getting them, if there's not after checking). Is there any option to do this?

Thanks.

mime.extension is not a function

EDIT: There is nothing to do with the code block below (with if(mail.attachments), it has problem without it as well)

I basically try the code on #16

notifier(imap)
  .on('mail', mail => {
    console.log(mail);
    if(mail.attachments) {
        mail.attachments.forEach(function(attachment){
          console.log('attachment.generatedFileName',attachment.generatedFileName)
            var bufferStream = new stream.Transform();
            bufferStream.push(attachment.content);
            var output = fs.createWriteStream('/tmp/' + attachment.generatedFileName);
            bufferStream.pipe(output);
        });
    }
  })
  .start();

I try an email with a basic image attachment and I got this error:

/Users/yasin/dev/maildeneme/node_modules/mail-notifier/node_modules/mailparser/lib/mailparser.js:1407
        defaultExt = mime.extension(contentType);
                          ^

TypeError: mime.extension is not a function
    at MailParser._generateFileName (/Users/yasin/dev/maildeneme/node_modules/mail-notifier/node_modules/mailparser/lib/mailparser.js:1407:27)
    at MailParser._processStateHeader (/Users/yasin/dev/maildeneme/node_modules/mail-notifier/node_modules/mailparser/lib/mailparser.js:309:61)
    at MailParser._process (/Users/yasin/dev/maildeneme/node_modules/mail-notifier/node_modules/mailparser/lib/mailparser.js:227:22)
    at runCallback (timers.js:800:20)
    at tryOnImmediate (timers.js:762:5)
    at processImmediate [as _immediateCallback] (timers.js:733:5)

Issue on a dependency - CVE-2022-25883

Hi,

Good day.
Just wanted to inform that we encountered a security issue on one of mail-notifier dependency for its version 0.5.0:

Dependency: semver
Version: 5.3.0

It is raised under this CVE ID: CVE-2022-25883

If this was already discussed and resolution was already delivered. Let us know.
Thank you.

Encoding not recognized: 'UTF-32LE'

I'm getting these errors logged when receiving certain emails.

Error: Encoding not recognized: 'UTF-32LE' (searched as: 'utf32le')
    at Object.getCodec (.\node_modules\iconv-lite\lib\index.js:106:23)
    at Object.getDecoder (.\node_modules\iconv-lite\lib\index.js:127:23)
    at Object.decode (.\node_modules\iconv-lite\lib\index.js:40:25)
    at convertIconvLite (.\node_modules\encoding\lib\encoding.js:91:26)
    at convert (.\node_modules\encoding\lib\encoding.js:51:22)
    at Object.decodeBase64 (.\node_modules\mimelib\lib\mimelib.js:257:16)
    at Object.decodeMimeWord (.\node_modules\mimelib\lib\mimelib.js:330:25)
    at Object.module.exports.decodeMimeWord (.\node_modules\mimelib\lib\mimelib.js:64:41)
    at MailParser.<anonymous> (.\node_modules\mail-notifier\node_modules\mailparser\lib\mailparser.js:1395:24)
    at String.replace (<anonymous>)

0.2.0 doesn't work anymore

Hi there,

Updated to 0.2.0 and now it doesn't work anymore. Changed the secure to tls with tlsoption and at least now it can sign in to email again but not into the mailbox (it that makes any sense).

0.2.0 shows:
Express server listening on port 3000
28 Mar 16:35:42 - no new mail in INBOX

0.1.1 shows:
Express server listening on port 3000
28 Mar 16:35:41 - successfully opened mail box
28 Mar 16:35:42 - no new mail in INBOX

0.1.1 successfully fetches emails and parses them where as 0.2.0 does nothing. No erros anywhere to be seen.

Connected event isn't working

I'm trying to do something when the connection is establish, but the event don't seem to work for me. I'm recieving my mails but this event won't work.

Alternative :

`
var notifier = require('mail-notifier');

var imap = { // your configs ...}

notifier = notifier(imap);

notifier.on('mail', function(mail) { // do something.. }

notifier.start();

notifier.imap.on('ready', function() { // You are now connected! });

`

How can watch mails received in SPAM box ?

const imap = {
user: "yourimapuser",
password: "yourimappassword",
host: "imap.host.com",
port: 993, // imap port
tls: true,// use secure connection
tlsOptions: { rejectUnauthorized: false }
box:['INBOX','SPAM'] // is it correct ?
};

body of the email

i was trying to read the body but when i check the
message: mail.text && mail.text.replace(/\s/g,'').length > 0? mail.text : 'No Message body',
it syas that mail.text is undefined and thus automaticly says no message body. please help

markSeen False = duplicate emails

If markSeen is equal to false and i have 5 unread emails and a new email comes in, it triggers the on mail function 6 times, 5 for the existing unread emails and once for the new email.

Is this a feature or a bug... bug for my use case anyway

Unable to get the list of sent mails

I was trying to get the list of sent emails by changing box option to [Gmail]/Sent Mail, but i didn't get any response,
on the other hand INBOX works fine

if u have any suggestions or corrections, i need your help
thanks

duplicate email notification

i'm using the module to check an exchange mail box, but on 1000/1200 messages received per day, i've got more than 100/150 duplicates notifications.
anyone the same issue ?
thanks

Error event doesn't seem to work

If I have an error event attached, it somehow doesn't seem to trigger. All I'm getting is the "normal" error message, but I can't catch the error.

Am I doing this wrong?

notifier(imap_notifier).on('mail', function(mail){
    // Get the to address
    var _to = mail.to[0].address;
    // Call method to fetch and parse messages
    _connectMe(_to);
}).start();

notifier(imap_notifier).on('error', function(err){
     log.error('There is an error connecting to the IMAP server. Please check your setting!', err);
});


imap.fetch is not firing end event and it causes no mail event for new emails

I am trying to implement, email notifier for outlook IMAP. As soon as the IMAP server receives an email, my nodejs code need to process that.

This is how I am listening to mail event.

imap.openBox('INBOX', false, function (err, box) {
if (err) {
console.log("Error oppening inbox");
} else {
imap.on('mail', function (numNewMsgs) {
console.log("messages has arrived");
fetchMessages(imap);
});
}
});

// This is the code to fetch new email which is unseen and has recent flag
function fetchMessages(imap) {

var query = imap.search(['UNSEEN', 'RECENT'], function (error, results) {
if (error) { console.log("ERROR imap.search"); throw err; }

  if (results.length <= 0) return;

  var fetchQuery = imap.fetch(results, { bodies: '', markSeen: true });

  fetchQuery.on('message', function (msg, seqno) {
     // parseMessage(msg, seqno);
     console.log('New mail received.');

     var uid, flags;

     msg.once('attributes', function (attrs) {
        uid = attrs.uid;
        flags = attrs.flags;
     });

     var mp = new MailParser();
     mp.once('end', function (mail) {
        mail.uid = uid;
        mail.flags = flags;
        console.log("new email from mail parser");
        //self.emit('mail', mail);
        //self.dbg('found mail '+mail.headers["message-id"]);
     });

     msg.on('body', function (stream, info) {
        stream.pipe(mp);
     });

     msg.once('end', function () {
        // console.log(prefix + 'Finished');
     });
  });

  fetchQuery.once('error', function (err) {
     console.log('Fetch error: ' + err);
  });

  fetchQuery.once('end', function () {
     console.log('Done fetching all messages');
     imap.end();
  });

});
}

My problem is, the first time when I start my node js server, I am able to receive the "mail" event, but after that, I see I don't get any mail notification. It requires me to restart the node js server.

Based on my speculation I found, fetch query "end" event never gets fired.

I tried IMAP.seq.fetch query example from the git hub which works fine, I see end event, but here with imap.fetch I don't get end event.

Note: I am testing this on Outlook IMAP. (Gmail IMAP is working fine for me.)
Please let me know what I am doing wrong. Thanks in advance.

This error is thrown sporadically when services has been active for awhile

throw er; // Unhandled 'error' event
^

Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1135:19)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at TLSSocket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

Versioning of this project

It seems strange how this project is handling the releases, the current version is 0.5.0 where some commits that currently resides in the master branch are not there, like emitting an end when a connection is closed. this is a critical fix IMO, so adding this by repo gives a version of 0.4.1 which is really strange.

Anyone has an idea about the versioning control in this project ?

Event for when mail-notifier connects to IMAP

I'm looking to be able to trigger a message when successful connection to the IMAP server occurs. This is something the outdated mail-listener2 module provided. Is there anyway to get this out of the existing implementation? If not, any plans to add this? I can take a look at creating a PR I just don't have time to dig through the code at the moment.

Thanks!

method invocation after mail read

I was wondering if there is a method that gets triggered or ways to loop over all mails once all email/attachments have been read so an external process can start?

connected status.

It would be better to set connected to false before emitting 'end' event and checking if imap is connected before emitting 'error' event.

Only able to connect two listeners?

I've been using mail-notifier for testing email delivery in some e2e tests using protractor. In general the library is working as expected; however, I am noticing when I try to run three listeners at once I am running into issues in that all the listeners throw, 'Error: LOGIN failed.'; however, two listeners appear to be working fine. Below is my sanitized code for my email util. I am starting the mail listeners before the execution of my test cases and simply checking the arrays in my test cases. Any help is appreciated!

const temp00Notifier = require('mail-notifier');
const temp01Notifier = require('mail-notifier');
const temp02Notifier = require('mail-notifier');

const temp00RecievedEmails: Array<object> = [];
const temp01RecievedEmails: Array<object> = [];
const temp02RecievedEmails: Array<object> = [];

export async function startTemp00MailListener() {
  const imap = {
    user: '[email protected]',
    password: 'Password',
    host: 'sampleHost.com',
    port: 993,
    tls: true,
    tlsOptions: { rejectUnauthorized: false },
  };
  await temp00Notifier(imap).on('mail', (mail: any) => temp00RecievedEmails.push(mail)).start();
}

export async function startTemp01MailListener() {
  const imap = {
    user: '[email protected]',
    password: 'Password',
    host: 'sampleHost.com',
    port: 993,
    tls: true,
    tlsOptions: { rejectUnauthorized: false },
  };
  await temp01Notifier(imap).on('mail', (mail: any) => temp01RecievedEmails.push(mail)).start();
}

export async function startTemp02MailListener() {
  const imap = {
    user: '[email protected]',
    password: 'Password',
    host: 'sampleHost.com',
    port: 993,
    tls: true,
    tlsOptions: { rejectUnauthorized: false },
  };
  await temp02Notifier(imap).on('mail', (mail: any) => temp02RecievedEmails.push(mail)).start();
}

export async function getTemp00RecievedEmails() {
  return temp00RecievedEmails;
}

export async function getTemp01RecievedEmails() {
  return temp01RecievedEmails;
}

export async function getTemp02RecievedEmails() {
  return temp02RecievedEmails;
}

ECONNRESET

{ Error: read ECONNRESET at _errnoException (util.js:1019:11) at TCP.onread (net.js:608:25) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read', source: 'socket' }

I see those constantly. What's causing it?

Unable to stream attachments

I understand that mail-notifier is using mailparser under the hood but the option of streamAttachments is not exposed in this module that would allow for streaming of attachments rather than giving us buffers which can be a headache.

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.