Download parts of email message
Some times you know you’ll receive large emails, and you only need to access some parts without downloading entire messages .
Mail.dll .NET IMAP client allows you to download only needed parts of the specified message.
First you need to get the structure of the message.
There are two methods for that: GetBodyStructureByUID and GetBodyStructure.
You can also use GetMessageInfo or GetMessageInfoByUID methods.
Both methods return more information about the email (subject, from, to and other headers) and include BodyStructure in their response.
BodyStructure contains information about plain text, html, and all attachments of the message. It does not contain any data though.
To download text parts of the email (like html or plain text) you can use: GetMimePartTextByUID or GetMimePartText.
To download attachments use: GetMimePartByUID or GetMimePart.
Here’s the full sample for this feature:
// 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)
{
// Get the structure of the email
BodyStructure structure = imap.GetBodyStructureByUID(uid);
// Download only text and html parts
string text = imap.GetMimePartTextByUID(uid, structure.Text);
string html = imap.GetMimePartTextByUID(uid, structure.Html);
Console.WriteLine(text);
Console.WriteLine(html);
// Show all attachments' filenames
foreach(MimeStructure attachment in structure.Attachments)
{
Console.WriteLine(attachment.SafeFileName);
// You can also download entire attachment
byte[] bytes = imap.GetMimePartByUID(uid, attachment);
}
}
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
' Get the structure of the email
Dim struct As BodyStructure = imap.GetBodyStructureByUID(uid)
' Download only text and html parts
Dim text As String = imap.GetMimePartTextByUID(
uid, struct.Text)
Dim html As String = imap.GetMimePartTextByUID(
uid, struct.Html)
Console.WriteLine(text)
Console.WriteLine(html)
' Show all attachments' filenames
For Each attachment As MimeStructure In struct.Attachments
Console.WriteLine(attachment.SafeFileName)
' You can also download entire attachment
Dim bytes As Byte() = imap.GetMimePartByUID(
uid, attachment)
Next
Next
imap.Close()
End Using

September 16th, 2010 at 18:56
[...] You can read more about downloading email parts (single attachment) here [...]
September 19th, 2010 at 21:15
How do you do this in POP3?
September 20th, 2010 at 12:30
@Franz You can’t do it using POP3 protocol.
POP3 is much simpler than IMAP and does not have all advanced features IMAP has.
You can find POP3 vs IMAP comparison here: http://www.lesnikowski.com/blog/pop3-vs-imap/