MailBee.NET Objects 4.0

Envelope Class

Represents an IMAP4 envelope of a mail message (including any other related information such as body structure, message flags, the mail message itself, etc).

For a list of all members of this type, see Envelope Members.

System.Object
   MailBee.ImapMail.Envelope

public class Envelope

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

Remarks

An instance of this class represents the information about the mail message returned by the IMAP4 server in a single FETCH response. This may contain information about an IMAP4 envelope (which is a collection of common properties of a mail message such as "Subject:", "From:", "To:", etc), a body structure of the mail message, the mail message itself, its flags, ordinal message number, UID, and size, the date when the message was received by the IMAP4 server, and other message attributes including user-specified ones.

MailBee allows the developer to specify which attributes/parts of mail messages must be downloaded resulting in a greater flexibility and smaller network traffic (unnecessary items are not downloaded).

All methods of Imap object which return MailMessage or MailMessageCollection objects actually download envelopes and then extract mail messages from MessagePreview property of Envelope object.

Note   Due to complexity of the IMAP4 protocol, many IMAP4 server implementations cannot always produce correct FETCH responses. If MailBee detects the particular FETCH response cannot be parsed, it raises ErrorOccurred event for this response, and sets IsValid property for the corresponding response to false. No exception is thrown, however.
Most fields of the envelope may be missing (if they were not requested from the server or they are missing in the message itself). For instance, if the message has no subject, Subject property may return a null reference (Nothing in Visual Basic). To make using Envelope object easier, MailBee returns empty values instead of null references by default. To force MailBee return a null reference for a missing field, the developer should set SafeMode to false.

Example

This sample downloads essential information about the messages in the inbox (such as IMAP4 envelope, date of receiving by the server, flags, and size), and its body structure. The messages themselves are not downloaded. The body structure information is used to count attachments of the message (this approach is more reliable than downloading message header and relying on HasAttachments property which might not be 100% correct). To notify user about particular envelopes which cannot be parsed, ErrorOccurred event handler is used.

[C#]
using System;
using MailBee;
using MailBee.ImapMail;

class Sample
{
    // ErrorOccurred event handler
    private static void OnErrorOccurred(object sender, ErrorEventArgs e)
    {
        // Filter only those errors which correspond to envelopes which cannot be parsed.
        MailBeeImapInvalidEnvelopeException ex =
            e.Reason as MailBeeImapInvalidEnvelopeException;

        if (ex != null)
        {
            Console.WriteLine("WARNING: IMAP response for message #" +
                ex.InvalidEnvelope.MessageNumber + " is incorrect.");
        }
}

    // The actual code
    static void Main(string[] args)
    {
        Imap imp = new Imap();

        // Attach ErrorOccurred event handler.
        imp.ErrorOccurred += new ErrorEventHandler(OnErrorOccurred);

        // Get to inbox.
        imp.Connect("imap.domain.com");
        imp.Login("jdoe", "secret");
        imp.SelectFolder("Inbox");

        // Get envelopes, body structures, message flags, etc for all messages in the inbox.
        EnvelopeCollection envelopes = imp.DownloadEnvelopes(
            Imap.AllMessages, false, EnvelopeParts.MailBeeEnvelope | EnvelopeParts.BodyStructure, 0);

        // Demonstrate that we can work with downloaded envelopes even in offline mode.
        imp.Disconnect();

        foreach (Envelope envelope in envelopes)
        {
            if (envelope.IsValid)
            {
                Console.WriteLine("Message #" + envelope.MessageNumber +
                    ", Received at: " + envelope.DateReceived + ", Created at: " + envelope.Date);
                Console.WriteLine("  Flags: " + envelope.Flags.ToString());
                Console.WriteLine("  From: " + envelope.From.ToString());
                Console.WriteLine("  To: " + envelope.To.ToString());
                Console.WriteLine("  Subject: " + envelope.Subject);
                System.Text.StringBuilder strBuffer = new System.Text.StringBuilder();
                ImapBodyStructureCollection parts = envelope.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"))
                    {
                        string filename;
                        if (part.Filename != null && part.Filename.Length > 0)
                        {
                            filename = part.Filename;
                        }
                        else
                        {
                            filename = "untitled";
                        }

                        // Important: Size property returns the length of part data in encoded form
                        // (such as base64). There is no way to learn the exact length unless to
                        // download the entire message. However, you may improve precision by examining
                        // MailEncodingName property value. If it's "base64", decoded data is about 70%
                        // in size of mail-encoded data. However, it's hard to estimate if it's
                        // "quoted-printable" because decoded size/encoded size ratio highly depends on
                        // the actual data contents in this case. Fortunately, "quoted-printable" is
                        // quite rarely used for attachments. If MailEncodingName is "", "binary", "7bit",
                        // or "8bit", then the data is not encoded, and Size property strictly matches
                        // the actual data length.
                        strBuffer.Append("[" + filename + " of approx. " + part.Size + " bytes]");
                    }
                }
                if (strBuffer.Length > 0)
                {
                    Console.WriteLine("  Attachments: " + strBuffer.ToString());
                }
                else
                {
                    Console.WriteLine("  Attachments: none");
                }
            }
            else
            {
                Console.WriteLine("Could not parse envelope for message #" + envelope.MessageNumber);
            }
        }
    }
}
[Visual Basic]
Imports System
Imports MailBee
Imports MailBee.ImapMail

Module Sample
    ' ErrorOccurred event handler
    Private Sub OnErrorOccurred(ByVal sender As Object, ByVal e As ErrorEventArgs)
        ' Filter only those errors which correspond to envelopes which cannot be parsed.
        Dim ex As MailBeeImapInvalidEnvelopeException = e.Reason

        If Not ex Is Nothing Then
            Console.WriteLine("WARNING: IMAP response for message #" & _
                ex.InvalidEnvelope.MessageNumber & " is incorrect.")
        End If
    End Sub

    ' The actual code
    Sub Main(ByVal args As String())
        Dim imp As New Imap

        ' Attach ErrorOccurred event handler.
        AddHandler imp.ErrorOccurred, AddressOf OnErrorOccurred

        ' Get to inbox.
        imp.Connect("imap.domain.com")
        imp.Login("jdoe", "secret")
        imp.SelectFolder("Inbox")

        ' Get envelopes, body structures, message flags, etc for all messages in the inbox.
        Dim envelopes As EnvelopeCollection

        envelopes = imp.DownloadEnvelopes(Imap.AllMessages, False, EnvelopeParts.MailBeeEnvelope _
            Or EnvelopeParts.BodyStructure, 0)

        ' Demonstrate that we can work with downloaded envelopes even in offline mode.
        imp.Disconnect()

        For Each env As Envelope In envelopes
            If env.IsValid Then
                Console.WriteLine("Message #" & env.MessageNumber & ", Received at: " & _
                    env.DateReceived & ", Created at: " & env.Date)
                Console.WriteLine(" Flags: " & env.Flags.ToString())
                Console.WriteLine(" From: " & env.From.ToString())
                Console.WriteLine(" To: " & env.To.ToString())
                Console.WriteLine(" Subject: " & env.Subject)

                Dim strBuffer As New System.Text.StringBuilder
                Dim parts As ImapBodyStructureCollection = env.BodyStructure.GetAllParts()

                For Each part As ImapBodyStructure In parts
                    ' Detect if this part is attachment.
                    If (Not part.Disposition Is Nothing AndAlso part.Disposition.ToLower() = "attachment") OrElse _
                        (Not part.Filename Is Nothing AndAlso part.Filename <> String.Empty) OrElse _
                        (Not part.ContentType Is Nothing AndAlso part.ContentType.ToLower() = "message/rfc822") Then

                        Dim filename As String

                        If (Not part.Filename Is Nothing) And (part.Filename.Length > 0) Then
                            filename = part.Filename
                        Else
                            filename = "untitled"
                        End If

                        ' Important: Size property returns the length of part data in encoded form
                        ' (such as base64). There is no way to learn the exact length unless to
                        ' download the entire message. However, you may improve precision by examining
                        ' MailEncodingName property value. If it's "base64", decoded data is about 70%
                        ' in size of mail-encoded data. However, it's hard to estimate if it's
                        ' "quoted-printable" because decoded size/encoded size ratio highly depends on
                        ' the actual data contents in this case. Fortunately, "quoted-printable" is
                        ' quite rarely used for attachments. If MailEncodingName is "", "binary", "7bit",
                        ' or "8bit", then the data is not encoded, and Size property strictly matches
                        ' the actual data length.
                        strBuffer.Append("[" & filename & " of approx. " & part.Size & " bytes]")
                    End If
                Next

                If strBuffer.Length > 0 Then
                    Console.WriteLine(" Attachments: " & strBuffer.ToString())
                Else
                    Console.WriteLine(" Attachments: none")
                End If
            Else
                Console.WriteLine("Could not parse envelope for message #" & env.MessageNumber)
            End If
        Next
    End Sub
End Module

Requirements

Namespace: MailBee.ImapMail

Assembly: MailBee.NET (in MailBee.NET.dll)

See Also

Envelope Members | MailBee.ImapMail Namespace | DownloadEnvelopes