Peek message on IMAP server

When you access messages stored on IMAP server, it automatically adds Seen flag to the messages you have downloaded.

If you don’t want this behavior, there are two things you can do.

First is to use Examine method instead of Select:

// C#

using(Imap imap = new Imap())
{
    imap.Connect("imap.server.com");
    imap.Login("user", "password");

    imap.ExamineInbox(); // -or- imap.Examine("Inbox");

    // ...

    imap.Close();
}
' VB.NET

Using imap As New Imap
    imap.Connect("imap.server.com")
    imap.Login("user", "password")

    imap.SelectInbox()

    imap.ExamineInbox() ' -or- imap.Examine("Inbox")

    ' ...

    imap.Close()
End Using

Examine puts mailbox (also called folder) into read-only state, so no Seen flag is added.
The drawback is that you can not delete a message.

Second approach is to use one of the Peek methods on the IMAP client:

// C#

using(Imap imap = new Imap())
{
    imap.Connect("imap.server.com");
    imap.Login("user", "password");

    imap.SelectInbox();
    List<long> uidList = imap.SearchFlag(Flag.Unseen);
    foreach (long uid in uidList)
    {
        IMail email = new MailBuilder()
            .CreateFromEml(imap.PeekMessageByUID(uid));
        Console.WriteLine(email.Subject);
    }
    imap.Close();
}
' VB.NET

Using imap As New Imap
    imap.Connect("imap.server.com")
    imap.Login("user", "password")

    imap.SelectInbox()
    Dim uidList As List(Of Long) = imap.SearchFlag(Flag.Unseen)

    For Each uid As Long In uidList
        Dim email As IMail = New MailBuilder() _
            .CreateFromEml(imap.PeekMessageByUID(uid))
        Console.WriteLine(email.Subject)
    Next
    imap.Close()
End Using

There are Peek methods for downloading headers and even parts of the email message.

You can download Mail.dll IMAP client here.

Tags: , , ,

3 Responses to “Peek message on IMAP server”

  1. Tweets that mention Peek message on IMAP server -- Topsy.com Says:

    [...] This post was mentioned on Twitter by Pawel Lesnikowski. Pawel Lesnikowski said: Peek message on #IMAP servers in #.NET: http://www.lesnikowski.com/blog/peek-message-on-imap-server/ [...]

  2. Nimesh Says:

    Is it possible to fetch all messages received from a particular email address using IMAP?

    I want to fetch all messages in my InBox which have originated from abc@xyz.com

  3. Pawel Lesnikowski Says:

    @Nimesh

    Use search method:

    List uids = client.Search().Where(Expression.From(“alice@example.com”));

    You can find more on this searching IMAP here:
    http://www.lesnikowski.com/blog/how-to-search-imap-in-net

Leave a Reply