How can I get only unread emails using imapflow?

3.5k Views Asked by At

Good morning, I am using this library at work and I have a problem.

When I connect to the imapflow mail server it returns all the mails but I can't differentiate which ones are read and which ones are not read.

I have been reading the documentation (https://imapflow.com/) but I can't find anything that helped me. I have also tried using filters but nothing works.

Could you please help me?

I leave the code snippet where I am trying to get the unread emails.

Thank you very much for your help.

    const main = async (client) => {

let envelope = [];

await client.connect();

// At this point I have set the variable unseen to true but it doesn't work :(
let lock = await client.getMailboxLock('INBOX', {unseen: true});

try {
    let message = await client.fetchOne('*', { source: true });
    //console.log(message.source.toString());

    for await (let message of client.fetch('1:*', { envelope: true })) {
        
        envelope.push(message.envelope)
    }
} finally {
    lock.release();
}

await client.logout();

let reverse_envelope = envelope.reverse();

return reverse_envelope
};
1

There are 1 best solutions below

0
STh On

With imapflow, the solution is quite simple:

You can use client.fetch() method with a SearchObject as first parameter. As second parameter, you can use FetchQueryObject:

await client.fetch({ seen: false }, { envelope: true });

What you pass in as FetchQueryObject may vary, and you can pass different options to the SearchObject, too, more info can be found in the docs :)

I am using this code:

let emails; 
for await (let msg of client.fetch(
      { seen: false },
      {
        flage: true,
        envelope: true,
        source: false,
        bodyParts: true,
        bodyStructure: true,
        uid: true, 
      }
    )) {
      emails.push(msg);
    }
// use emails here

But: Make sure that you only use this code in when you currently locked the Mailbox, otherwise you will always get an empty array as result.