1

I'm using GemBox.Email and I'm retrieving unread emails from my inbox like this:

using (var imap = new ImapClient("imap.gmail.com"))
{
    imap.Connect();
    imap.Authenticate("username", "password");
    imap.SelectInbox();

    IEnumerable<string> unreadUids = imap.ListMessages()
        .Where(info => !info.Flags.Contains(ImapMessageFlags.Seen))
        .Select(info => info.Uid);

    foreach (string uid in unreadUids)
    {
        MailMessage unreadEmail = imap.GetMessage(uid);
        unreadEmail.Save(uid + ".eml");
    }
}

The code is from the Receive example, but the problem is that after retrieving them they end up being marked as read in my inbox.

How can I prevent this from happening?
I want to download them with ImapClient and leave them as unread on email server.

Mario Z
  • 4,328
  • 2
  • 24
  • 38
hertzogth
  • 236
  • 1
  • 2
  • 19
  • I don’t know this library specifically, but there should be a way to pass the PEEK flag so it doesn’t mark it read when you do GetMessage. – Max May 07 '20 at 13:56
  • Amazingly, this library doesn’t seem to implement the PEEK flag for fetching messages, as far as I can tell from the documentation. Perhaps a feature request? – Max May 07 '20 at 14:00

1 Answers1

2

EDIT (2021-01-19):

Please try again with the latest version from the BugFixes page or from NuGet.

The latest version provides ImapClient.PeekMessage methods which you can use like this:

using (var imap = new ImapClient("imap.gmail.com"))
{
    imap.Connect();
    imap.Authenticate("username", "password");
    imap.SelectInbox();

    foreach (string uid in imap.SearchMessageUids("UNSEEN"))
    {
        MailMessage unreadEmail = imap.PeekMessage(uid);
        unreadEmail.Save(uid + ".eml");
    }
}

ORIGINAL:

When retrieving an email, most servers will mark it with the "SEEN" flag. If you want to leave an email as unread then you can just remove the flag.

Also, instead of using ImapClient.ListMessages you could use ImapClient.SearchMessageUids to get IDs of unread emails.

So, try the following:

using (var imap = new ImapClient("imap.gmail.com"))
{
    imap.Connect();
    imap.Authenticate("username", "password");
    imap.SelectInbox();

    // Get IDs of unread emails.
    IEnumerable<string> unreadUids = imap.SearchMessageUids("UNSEEN");
    
    foreach (string uid in unreadUids)
    {
        MailMessage unreadEmail = imap.GetMessage(uid);
        unreadEmail.Save(uid + ".eml");

        // Remove "SEEN" flag from read email.
        imap.RemoveMessageFlags(uid, ImapMessageFlags.Seen);
    }
}
Mario Z
  • 4,328
  • 2
  • 24
  • 38