ImapDownloadEnvelopes Method (String, Boolean, EnvelopeParts, Int32)
Fetches message envelopes, bodies, headers, flags, attributes, and other message-related information from the server.

Namespace: MailBee.ImapMail
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.4 build 677 for .NET 4.5
Syntax
public EnvelopeCollection DownloadEnvelopes(
	string messageIndexSet,
	bool indexIsUid,
	EnvelopeParts parts,
	int bodyPreviewSize
)

Parameters

messageIndexSet
Type: SystemString
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
Type: SystemBoolean
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Type: MailBee.ImapMailEnvelopeParts
Specifies which message elements or attributes to download.
bodyPreviewSize
Type: SystemInt32
If parts includes MessagePreview flag, specifies the length of the message body section (in bytes) to be downloaded in addition to the message header section; if 0, only the message header is downloaded; if -1 or -2, the entire message is downloaded. -1 is the only option which also sets Seen flag marking the message as read.

Return Value

Type: EnvelopeCollection
EnvelopeCollection object if message envelopes were downloaded successfully; otherwise, a null reference (Nothing in Visual Basic).
Exceptions
ExceptionCondition
MailBeeExceptionAn error occurred and ThrowExceptions is true.
Remarks

Ordinal message numbers and UIDs are one-based (minimum value is 1, not 0). However, the returned EnvelopeCollection is zero-based. The developer can use MessageNumber or Uid properties to obtain ordinal message numbers and UIDs of the downloaded envelopes.

To specify multiple message numbers or UIDs in messageIndexSet, delimit them with comma (,) or use ranges (such as "5:10" which means "download messages in the range from message #5 to the message #10"). Wildcard character (*), can be used to specify range which spans till the last message in the folder. In particular, "1:*" means "download all messages in the folder". "1:*" is also declared as AllMessages constant.

Examples of valid message sequences: "1", "1:*", "1,2", "1:2", "5:10,12:45,99,101,105,141:*".

Note Note
A message sequence string may NOT contain whitespaces. The following is INCORRECT: "1, 2, 5". The correct one is: "1,2,5".

When using a range of UIDs (indexIsUid is true), it's important to understand the number of returned messages may be LESS than the length of the range (or even zero). This is because UIDs are not continuous. For instance, if the folder contains messages with UIDs 4, 5, 6, 10, and 22, the "1,2,8:20" sequence of UIDs corresponds to a single message with UID=10.

parts parameters can be used to specify which message elements to download. This allows the developer to request only required information from the server and thus reduce network traffic by not downloading unnecessary data.

Note Note
If certain message element, attribute, or group of elements/attributes is not requested from the server, the developer should not attempt to read the corresponding properties of Envelope objects within the returned collection. For instance, if parts didn't contain Envelope (or MailBeeEnvelope, which is a superset of Envelope), From, To, Subject, and some other properties will not return useful information. See remarks in EnvelopeParts topic for more information on dependencies between downloaded parts of FETCH response and related properties of Envelope object.

bodyPreviewSize parameter makes sense only when parts includes MessagePreview flag. When bodyPreviewSize is 0, the component will download only header section of each message (accessible via MessagePreview property). If bodyPreviewSize is larger than 0, the component will download the header and the specified count of bytes of the body. If bodyPreviewSize is -1 or -2, the entire message is returned (-2 will keep UNSEEN status). Methods like DownloadEntireMessage(Int64, Boolean) or DownloadMessageHeaders(String, Boolean) simply call DownloadEnvelopes(String, Boolean, EnvelopeParts, Int32, String, String) inside and then return MessagePreview values.

Note Note
Due to complexity of IMAP4 responses, some servers may return badly formed FETCH responses under certain circumstances. If MailBee detects this, it raises ErrorOccurred event and sets IsValid to false. Since this is done on per-envelope basis, some Envelope objects in the returned collection may have IsValid set to false while others - to true. Anyway, the component does not throw exception when it encounters invalid envelope. This allows the application to skip invalid response and successfully receive subsequent messages.
Examples
For each message in the Inbox, this sample downloads the message preview (the message header section + first 1000 bytes of the body), the body structure (to correctly determine if the message has attachments), and the date of receiving the message by the server.
using System;
using MailBee;
using MailBee.ImapMail;
using MailBee.Mime;

class Sample
{
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        imp.Connect("mail.company.com");

        imp.Login("jdoe", "secret");

        // Select Inbox folder.
        imp.SelectFolder("Inbox");

        // Download body structure (header + 1000 bytes of the body), message preview,
        // and the date assigned to the message by the server (usually, it's the date
        // when the message was received by the server).
        EnvelopeCollection envs = imp.DownloadEnvelopes(Imap.AllMessages, false,
            EnvelopeParts.BodyStructure | EnvelopeParts.MessagePreview | EnvelopeParts.InternalDate,
            1000);

        foreach (Envelope env in envs)
        {
            Console.WriteLine("Message #" + env.MessageNumber + " info:");
            if (env.IsValid)
            {
                // Tell MailBee to create plain-text version of HTML message
                // if plain-text version is not available in the message.
                // It's important to set this before the message gets parsed
                // (which occurs automatically when any element of the message
                // is accessed though MailMessage object properties or methods).
                // If you change HtmlToPlainMode after the message has already been parsed,
                // call MailMessage.Parser.Apply to reparse the message with new settings.
                env.MessagePreview.Parser.HtmlToPlainMode = HtmlToPlainAutoConvert.IfNoPlain;

                Console.WriteLine("From: " + env.MessagePreview.From.ToString());
                Console.WriteLine("To: " + env.MessagePreview.To.ToString());
                Console.WriteLine("Subject: " + env.MessagePreview.Subject);
                Console.WriteLine("Composed at: " + env.MessagePreview.Date);

                // We use DateReceived from INTERNALDATE item of FETCH response.
                // We could have also used env.MessagePreview.DateReceived instead
                // (it's obtained from "Received:" headers of the message).
                // However, env.MessagePreview.DateReceived is DateTime.MinValue
                // when the message does not contain "Received:" headers.
                // INTERNALDATE, on other hand, is always available in IMAP4.
                // MailMessage.DateReceived still makes sense because INTERNALDATE
                // is not available in POP3, and examining "Received:" headers is
                // the only way of getting this info when using POP3 protocol.
                Console.WriteLine("Received at: " + env.DateReceived);

                if (env.MessagePreview.Priority >= MailPriority.High)
                {
                    Console.WriteLine("The message is high priority");
                }

                // Determine if the message has attachments.
                bool hasAttachments = false;
                ImapBodyStructureCollection parts = env.BodyStructure.GetAllParts();
                foreach (ImapBodyStructure part in parts)
                {
                    // Detect if this part is attachment.
                    if ((part.Disposition != null && part.Disposition.ToLower() == "attachment") ||
                        (part.Filename != null && part.Filename != string.Empty) ||
                        (part.ContentType != null && part.ContentType.ToLower() == "message/rfc822"))
                    {
                        hasAttachments = true;
                        break;
                    }
                }
                if (hasAttachments)
                {
                    Console.WriteLine("The message has attachments.");
                }

                // Display first 250 characters of the text body. Note that we requested
                // 1000 bytes but now display only 250 characters. We request more than
                // we display because of:
                // - body section of MIME message may start with a block of additional
                // information which is not a part of text body. Usually, the length
                // of this block is 100-300 bytes.
                // - non-ASCII characters may occupy more than one byte.
                // In some cases, reading 1000 bytes may still be not enough to reach the
                // text body (for instance, if the message contains attachment which preceeds
                // the text body in the message source). In such rare cases, the body preview
                // will not be available (or, the developer may request more than 1000 bytes
                // of the body and thus increase network traffic). 
                string bodyPreview = env.MessagePreview.BodyPlainText;
                if (bodyPreview.Length > 250)
                {
                    bodyPreview = bodyPreview.Substring(0, 250);
                }
                Console.WriteLine();
                Console.WriteLine(bodyPreview);
            }
            else
            {
                Console.WriteLine("FETCH response contains some invalid data.");
            }
            Console.WriteLine("============================================================");
        }

        // Disconnect from the server.
        imp.Disconnect();
    }
}
See Also