Mark emails as read using IMAP

In this article we’ll show how to mark emails as seen (read) using Mail.dll .NET IMAP library and IMAP protocol.

The following code connects to an IMAP server, finds unique ids of all unseen email messages and marks the first one as seen. Internally IMAP server uses IMAP flag \UNSEEN (Flag.Unseen) to remember which messages were already read by user.

// C# version

using(Imap imap = new Imap())
{
	imap.Connect("imap.example.com");    // or ConnectSSL for SSL
	imap.UseBestLogin("user", "password");

	imap.SelectInbox();
	List<long> uids = client.Search(Flag.Unseen);
	if (uids.Count > 0)
		client.MarkMessageSeenByUID(uids[0]);
    imap.Close();
}
' VB.NET version

Using imap As New Imap()
	imap.Connect("imap.example.com")    ' or ConnectSSL for SSL
	imap.UseBestLogin("user", "password")

	imap.SelectInbox()
	Dim uids As List(Of Long) = client.Search(Flag.Unseen)
	If uids.Count > 0 Then
		client.MarkMessageSeenByUID(uids(0))
	End If
	imap.Close()
End Using

If you are using GetMessageByUID to download email message or GetHeadersByUID to get only message headers, most IMAP servers will automatically mark such messages as seen. If it’s not expected behavior in your scenario, you can use Peek* methods: PeekHeadersByUID, PeekMessageByUID. Those methods in contrast to their Get* equivalents: GetMessageByUID and GetHeadersByUID do not set the Seen flag – emails are not marked as seen automatically.

You can also easily mark message as unseen by using Imap.MarkMessageUnseenByUID method.

Please note that it is not possible to mark messages as read using POP3 protocol. You can read more about differences between IMAP and POP3.

Tags: , , ,

Questions?

Consider using our Q&A forum for asking any questions.