Unread and read IMAP messages

0 votes
asked May 10, 2011 by Rebex KB (8,330 points)
edited Aug 19, 2014

I want to resolve whether the IMAP message is "read" or "unread". Then I'd like to mark message as "read". How to do it?

Applies to: Rebex Secure Mail

1 Answer

+1 vote
answered May 10, 2011 by Jan Sotola (16,930 points)
edited May 10, 2011
 
Best answer

Here is a tutorial that demonstrates working with read/unread (or seen/unseen) message flag on IMAP server:

Create client object, connect and set current folder:

   Imap client = new Imap();
   client.Connect("imap.example.com");
   client.Login("username", "password");

   client.SelectFolder("Inbox");

Count of unread messages is accessible directly through a property:

   Console.WriteLine("Unread messages count: {0}", client.CurrentFolder.NotSeenMessageCount);

List all unread messages in the folder:

   ImapMessageCollection list = client.Search(ImapSearchParameter.Unread);
   foreach (ImapMessageInfo msg in list)
         Console.WriteLine("Subject: {0}", msg.Subject);

Resolve (un)read status of individual message and change the status of the message:

   // get the topmost message in the folder
   ImapMessageInfo messageInfo = client.GetMessageInfo(client.CurrentFolder.TotalMessageCount, ImapListFields.Envelope);

   // resolve whether the message is read or unread
   bool unread = (int)(messageInfo.Flags & ImapMessageFlags.Seen) == 0;

   // write status of the message
   Console.WriteLine("Subject: {0} [{1}]", messageInfo.Subject, unread ? "UNREAD" : "read");

   // togle (un)read status of the message
   if (unread)
   {
         client.SetMessageFlags(messageInfo.SequenceNumber, ImapFlagAction.Add, ImapMessageFlags.Seen);
         Console.WriteLine("Setting as read...");
   }
   else
   {
         client.SetMessageFlags(messageInfo.SequenceNumber, ImapFlagAction.Remove, ImapMessageFlags.Seen);
         Console.WriteLine("Setting as unread...");
   }
...