MailBee.NET Objects 4.0

Imap.BeginDownloadEnvelopes Method 

Begins an asynchronous request for downloading the specified message elements (envelopes, flags, body structures, entire messages or message headers, etc) from the currently selected folder.

public IAsyncResult BeginDownloadEnvelopes(
   string messageIndexSet,
   bool indexIsUid,
   EnvelopeParts parts,
   int bodyPreviewSize,
   string[] extraHeaders,
   string[] extraItems,
   AsyncCallback callback,
   object state
);

Parameters

messageIndexSet
A message sequence string containing ordinal message numbers or UIDs. Can be composed manually or using ToString.
indexIsUid
If true, messageIndexSet is treated as a sequence of UIDs; otherwise, as a sequence of ordinal message numbers.
parts
Specifies which message elements or attributes to download.
bodyPreviewSize
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, the entire message is downloaded.
extraHeaders
The array of names of message headers to be downloaded, or a null reference (Nothing in Visual Basic) if additional headers are not needed.
extraItems
The array of additional FETCH request items to download, or a null reference (Nothing in Visual Basic) if additional FETCH items are not needed.
callback
The AsyncCallback delegate. You can leave it a null reference (Nothing in Visual Basic) if you do not use callbacks.
state
An object that contains state information for this request. You can leave it a null reference (Nothing in Visual Basic).

Return Value

An IAsyncResult that references the asynchronous downloading of envelopes or other message elements..

Remarks

This method is an asynchronous version of DownloadEnvelopes.

Exceptions

Exception Type Condition
MailBeeInvalidStateException There is already an operation in progress.

Example

This WinForms sample demonstrates asynchronous downloading of all new messages in the Inbox folder. The messages are downloaded completely (with attachments, text parts, etc) and saved into "C:\Temp" folder. The message flags are downloaded as well. For each message, the sample prints saved file name and flags into Output window (it's visible when the application is being run in debug mode).

[C#]
// To use the code below, import MailBee namespaces at the top of your code.
using MailBee;
using MailBee.ImapMail;

// Put the code below inside your class.

// The actual code.
private void Form1_Load(object sender, System.EventArgs e)
{
    Imap imp = new Imap();

    // We do not subscribe to any events in this sample, so we do not
    // need to care about them. However, if you decide to subscribe to
    // an event and your application will block message loop thread
    // using imp.Wait() method, you should uncomment the next line
    // to tell MailBee not to use message loop thread for raising events
    // and use imp.Wait() method instead of ar.AsyncWaitHandle.WaitOne(). 
    // imp.RaiseEventsViaMessageLoop = false;

    // Connect to the server, login and select inbox.
    imp.Connect("imap4.server.com");
    imp.Login("jdoe", "secret");
    imp.SelectFolder("Inbox");

    // Obtain UIDs of new messages (messages which are recent and unseen).
    UidCollection uids = (UidCollection)imp.Search(true, "NEW", null);

    EnvelopeCollection envs = null;

    if (uids.Count > 0)
    {
        // Asynchronously download entire messages and their flags.
        IAsyncResult ar = imp.BeginDownloadEnvelopes(uids.ToString(), true,
            EnvelopeParts.MessagePreview | EnvelopeParts.Flags, -1,
            null, null, null, null);

        // Wait until the asynchronous download completes. Note: this call
        // blocks UI. Thus, if you subscribe to any events, you'll got a
        // deadlock (because events will be raised only after message loop thread
        // gets un-blocked again, while WaitOne() method which blocked the message
        // loop will wait until all events get raised). The solution is to set
        // imp.RaiseEventsViaMessageLoop to false and use imp.Wait() method
        // instead of ar.AsyncWaitHandle.WaitOne() method.
        ar.AsyncWaitHandle.WaitOne();

        // Get downloaded envelopes (messages + flags).
        envs = imp.EndDownloadEnvelopes();
    }

    // Demonstrate that we may disconnect before finished with processing
    // of downloaded envelopes. Although in most samples we disconnect in
    // the very end of the code, it's more efficient to disconnect once the
    // connection is no longer needed. For instance, it may take considerable
    // amount of time to save downloaded messages in the folder (see below).
    // During this time, the connection with the server will just waste system
    // resources since the connection is not actually required any longer.
    // The same optimization can be applied to all other MailBee components.
    imp.Disconnect();

    if (envs != null)
    {
        // Save all downloaded messages into "C:\Temp" folder.
        // Each filename is generated as message's UID + ".eml".
        foreach (Envelope env in envs)
        {
            string filename = env.Uid + ".eml";
            env.MessagePreview.SaveMessage(@"C:\Temp\" + filename);

            // To see this report in VS.NET environment, run the sample
            // in debug mode and monitor the contents of Output window.
            System.Diagnostics.Debug.WriteLine("Message #" + env.MessageNumber +
                " having (" + env.Flags.ToString() + ") flags set was saved as " +
                filename);
        }
    }
}
[Visual Basic]
' To use the code below, import MailBee namespaces at the top of your code.
Imports MailBee
Imports MailBee.ImapMail

' Put the code below inside your class.

' The actual code.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim imp As New Imap

    ' We do not subscribe to any events in this sample, so we do not
    ' need to care about them. However, if you decide to subscribe to
    ' an event and your application will block message loop thread
    ' using imp.Wait() method, you should uncomment the next line
    ' to tell MailBee not to use message loop thread for raising events
    ' and use imp.Wait() method instead of ar.AsyncWaitHandle.WaitOne(). 
    ' imp.RaiseEventsViaMessageLoop = false

    ' Connect to the server, login and select inbox.
    imp.Connect("imap4.server.com")
    imp.Login("jdoe", "secret")
    imp.SelectFolder("Inbox")

    ' Obtain UIDs of new messages (messages which are recent and unseen).
    Dim uids As UidCollection = CType(imp.Search(True, "NEW", Nothing), UidCollection)

    Dim envs As EnvelopeCollection = Nothing

    If uids.Count > 0 Then
        ' Asynchronously download entire messages and their flags.
        Dim ar As IAsyncResult = imp.BeginDownloadEnvelopes(uids.ToString(), True, _
            EnvelopeParts.MessagePreview Or EnvelopeParts.Flags, -1, _
            Nothing, Nothing, Nothing, Nothing)

        ' Wait until the asynchronous download completes. Note: this call
        ' blocks UI. Thus, if you subscribe to any events, you'll got a
        ' deadlock (because events will be raised only after message loop thread
        ' gets un-blocked again, while WaitOne() method which blocked the message
        ' loop will wait until all events get raised). The solution is to set
        ' imp.RaiseEventsViaMessageLoop to false and use imp.Wait() method
        ' instead of ar.AsyncWaitHandle.WaitOne() method.
        ar.AsyncWaitHandle.WaitOne()

        ' Get downloaded envelopes (messages + flags).
        envs = imp.EndDownloadEnvelopes()
    End If

    ' Demonstrate that we may disconnect before finished with processing
    ' of downloaded envelopes. Although in most samples we disconnect in
    ' the very end of the code, it's more efficient to disconnect once the
    ' connection is no longer needed. For instance, it may take considerable
    ' amount of time to save downloaded messages in the folder (see below).
    ' During this time, the connection with the server will just waste system
    ' resources since the connection is not actually required any longer.
    ' The same optimization can be applied to all other MailBee components.
    imp.Disconnect()

    If Not envs Is Nothing Then
        ' Save all downloaded messages into "C:\Temp" folder.
        ' Each filename is generated as message's UID + ".eml".
        For Each env As Envelope In envs
            Dim filename As String = env.Uid & ".eml"
            env.MessagePreview.SaveMessage("C:\Temp\" & filename)

            ' To see this report in VS.NET environment, run the sample
            ' in debug mode and monitor the contents of Output window.
            System.Diagnostics.Debug.WriteLine("Message #" & env.MessageNumber & _
                " having (" & env.Flags.ToString() & ") flags set was saved as " & filename)
        Next
    End If
End Sub

See Also

Imap Class | MailBee.ImapMail Namespace | DownloadEnvelopes | DownloadEntireMessages | DownloadMessageHeaders