Peek message on IMAP server
If you are using GetMessageByUID to download email message or GetHeadersByUID to get email headers only, most IMAP servers will automatically mark such messages as seen.
In other words IMAP server adds \SEEN flag to the messages you have just downloaded.
If it’s not expected behavior in your scenario, you can use one of the Peek* methods, such as: PeekHeadersByUID, PeekMessageByUID.
Using Peek methods
Those methods in contrast to their Get* equivalents (GetMessageByUID and GetHeadersByUID) do not set the \SEEN flag – emails are not marked as seen automatically.
The sample below connects to IMAP server and finds all unseen messages, then it downloads them, but does not change their unseen status. Messages are left unseen.
// C#
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.example.com");
imap.UseBestLogin("user", "password");
imap.SelectInbox();
List<long> uidList = imap.Search(Flag.Unseen);
foreach (long uid in uidList)
{
IMail email = new MailBuilder()
.CreateFromEml(imap.PeekMessageByUID(uid));
string subject = email.Subject;
string text = email.Text;
}
imap.Close();
}
' VB.NET
Using imap As New Imap
imap.ConnectSSL("imap.example.com")
imap.UseBestLogin("user", "password")
imap.SelectInbox()
Dim uidList As List(Of Long) = imap.Search(Flag.Unseen)
For Each uid As Long In uidList
Dim email As IMail = New MailBuilder() _
.CreateFromEml(imap.PeekMessageByUID(uid))
Dim subject As String = email.Subject
Dim text As String = email.Text
Next
imap.Close()
End Using
There are Peek methods for downloading headers only (PeekHeadersByUID) and even parts of the email message (PeekTextByUID , PeekDataByUID).
Examine instead of Select
The second approach is to use Examine method instead of Select. Examine puts the folder into read-only state, so no \SEEN flag is added to any message.
The drawback is that you can not delete or upload any message.
// C#
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.example.com");
imap.UseBestLogin("user", "password");
imap.ExamineInbox(); // -or- imap.Examine("Inbox");
// ...
imap.Close();
}
' VB.NET
Using imap As New Imap
imap.ConnectSSL("imap.example.com")
imap.UseBestLogin"user", "password")
imap.ExamineInbox() ' -or- imap.Examine("Inbox")
' ...
imap.Close()
End Using
You can also easily mark message as seen and unseen by using Imap.MarkMessageUnseenByUID and Imap.MarkMessageSeenByUID methods.
You can download Mail.dll IMAP library for .NET here.
Get Mail.dll
May 20th, 2015 at 21:10
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
May 22nd, 2015 at 06:29
@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.limilabs.com/blog/how-to-search-imap-in-net