Download parts of email message
Thursday, July 8th, 2010Some 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

