chadxz / imap-simple

Wrapper over node-imap, providing a simpler api for common use cases
MIT License
243 stars 80 forks source link

How to retrieve new mail content with onMail event ? #85

Closed MateusDev98 closed 3 years ago

MateusDev98 commented 4 years ago

Hello,

I'm looking for a way to retrieve the content of the mail who triggered the onMail event. Is there a way to do it ?

john-yick commented 3 years ago

I too would like to know how to fetch the email message based off the numNewMail

minhnhut commented 3 years ago

I was facing same problem too. I am building a bot that read through all "UNSEEN" message in inbox, then do something with it depend on the content.

I have a function look like this, to fetch and process messages:

const fetchAndProcess = () => {
        const searchCriteria = [
            'UNSEEN'
        ];
        const fetchOptions = {
            bodies: ['HEADER', 'TEXT'],
            markSeen: false
        };
        connection.search(searchCriteria, fetchOptions).then(function (messages) {
            messages.forEach(function (item) {
                processEmail(item);
            });
        });
};

Then setup my imap-simple instance like this

// other config ...
config.onmail = fetchAndProcess;
client = await imaps.connect(config);
await connection.openBox('Inbux');

So basically, everytime there is a message coming, it will try fetch all again then do process. Pretty inefficient here, but acceptable for me .. for now.

lacajanegra commented 3 years ago

You can use an event that allows you to handle the arrival of new emails.

imaps.connect(config).then(function (connection) {
    connection.on('mail', () => {
      const searchCriteria = [
        'UNSEEN'
      ];
      const fetchOptions = {
        bodies: ['HEADER', 'TEXT'],
        markSeen: false
      };
      connection.search(searchCriteria, fetchOptions).then(function (messages) {
        messages.forEach(function (item) {
          console.log('item', item)
        });
      });
    })
    return connection.openBox('INBOX')
  })