IMAP: How to get e-mails including the message body

0 votes
asked Oct 18, 2012 by Rebex KB (8,190 points)
edited Oct 18, 2012

I'm trying to get all unread messages from my Inbox using the following code:

var client = new Imap();
client.Connect("server");
client.Login("username", "password");
client.SelectFolder("Inbox");

var list = client.Search(ImapSearchParameter.Unread);

foreach (ImapMessageInfo msg in list)
{
    Console.WriteLine("==Subject: {0}==", msg.Subject);
    Console.WriteLine("{0}", msg.BodyText);
    Console.WriteLine("{0}", msg.BodyHtml);
}

However, the body is always empty.

Applies to: Rebex Secure Mail

1 Answer

0 votes
answered Oct 18, 2012 by Jan Sotola (16,920 points)
edited Oct 18, 2012
 
Best answer

By default, the Search() or the GetMessageList() methods load the message envelope only. The envelope contains important message headers (such as Date, Subject, From, To or Message ID) but it does not contain the message body.

To obtain message body, use the ImapListFields.Body as an argument of the Search() or the GetMessageList() methods:

var client = new Imap();
client.Connect("server");
client.Login("username", "password");
client.SelectFolder("Inbox");

var list = client.Search(ImapListFields.Body, ImapSearchParameter.Unread);

foreach (ImapMessageInfo msg in list)
{
    Console.WriteLine("=====Subject: {0}=====", msg.Subject);
    Console.WriteLine("--Plain text--\r\n{0}", msg.BodyText);
    Console.WriteLine("--Html code--\r\n{0}", msg.BodyHtml);
    Console.WriteLine("====================================");
}

For more information about the ImapListFields see the Retrieving message list tutorial.

NOTE: To get the whole message (including all headers, body and attachments), you can also use the GetMailMessage() method. But use this method only when you really need it - it is much slower than the GetMessageList() or the Search() methods.

CAUTION: When retrieving the message body, the unread messages are marked as read. To prevent this behavior, add the following line of code:

client.Settings.UsePeekForGetMessage = true;

before calling the Search(), GetMessageList() or GetMailMessage() methods.

...