IMAP: Retrieving and Decoding Email Attachments and Message Parts


The IMAP component provides built-in support for retrieving and processing email message parts, including attachments. Depending on your requirements, you can either automatically decode message parts or selectively retrieve them to improve performance.

The AutoDecodeParts property controls whether message parts are automatically decoded. When set to true, the component decodes fetched messages, fires the MessagePart event for each part, and populates the MessageParts collection. To improve performance, this property is set to false by default.

A common approach is to first retrieve message metadata without downloading all content, and then selectively retrieve individual parts:

imap.MessageSet = "1";
imap.RetrieveMessageInfo();
foreach (MessagePart part in imap.MessageParts)
{
    imap.RetrieveMessagePart(part.Id);
}

Alternatively, you could go through each Part in the Message and download the attachments to disk:

imap.MessageSet = "1";
imap.RetrieveMessageInfo();
foreach (MessagePart part in imap.MessageParts)
{
    // if the part is an attachment, prepare for download
    if (part.FileName != "")
    {
        imap.LocalFile = "C:\\PATH\\TO\\" + part.FileName;
        imap.AutoDecodeParts = true;
    }
    // otherwise, see the part only in memory
    else
    {
        imap.LocalFile = "";
        imap.AutoDecodeParts = false;
    }
    imap.RetrieveMessagePart(part.Id);
}

In previous versions of IPWorks, you need to pass the message headers and text to the MIME component and decode the message manually. The MIME component will break apart the message into its separate parts.

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.