Click or drag to resize
MimeKit

ImapFolderGetBodyPart(UniqueId, String, CancellationToken, ITransferProgress) Method

Get the specified body part.

Namespace: MailKit.Net.Imap
Assembly: MailKit (in MailKit.dll) Version: 4.3.0
Syntax
C#
public virtual MimeEntity GetBodyPart(
	UniqueId uid,
	string partSpecifier,
	CancellationToken cancellationToken = default,
	ITransferProgress progress = null
)

Parameters

uid  UniqueId
The UID of the message.
partSpecifier  String
The body part specifier.
cancellationToken  CancellationToken  (Optional)
The cancellation token.
progress  ITransferProgress  (Optional)
The progress reporting mechanism.

Return Value

MimeEntity
The body part.

Implements

IImapFolderGetBodyPart(UniqueId, String, CancellationToken, ITransferProgress)
Exceptions
ExceptionCondition
ArgumentNullExceptionpartSpecifier is null.
ArgumentExceptionuid is invalid.
ObjectDisposedException The ImapClient has been disposed.
ServiceNotConnectedException The ImapClient is not connected.
ServiceNotAuthenticatedException The ImapClient is not authenticated.
FolderNotOpenException The ImapFolder is not currently open.
MessageNotFoundException The IMAP server did not return the requested message body.
OperationCanceledException The operation was canceled via the cancellation token.
IOException An I/O error occurred.
ImapProtocolException The server's response contained unexpected tokens.
ImapCommandException The server replied with a NO or BAD response.
Remarks
Gets the specified body part.
Example
C#
public static void DownloadBodyAndAttachments (string baseDirectory)
{
    using (var client = new ImapClient ()) {
        client.Connect ("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);

        client.Authenticate ("username", "password");

        client.Inbox.Open (FolderAccess.ReadOnly);

        // search for messages where the Subject header contains either "MimeKit" or "MailKit"
        var query = SearchQuery.SubjectContains ("MimeKit").Or (SearchQuery.SubjectContains ("MailKit"));
        var uids = client.Inbox.Search (query);

        // fetch summary information for the search results (we will want the UID and the BODYSTRUCTURE
        // of each message so that we can extract the text body and the attachments)
        var items = client.Inbox.Fetch (uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);

        foreach (var item in items) {
            // determine a directory to save stuff in
            var directory = Path.Combine (baseDirectory, item.UniqueId.ToString ());

            // create the directory
            Directory.CreateDirectory (directory);

            // IMessageSummary.TextBody is a convenience property that finds the 'text/plain' body part for us
            var bodyPart = item.TextBody;

            if (bodyPart != null) {
                // download the 'text/plain' body part

                // Note: In general, you should use `GetBodyPart(item.UniqueId, bodyPart)` instead if you have it available.
                // This particular overload of the GetBodyPart() method exists for convenience purposes where you already
                // know the body-part specifier string before-hand.
                var plain = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, bodyPart.PartSpecifier);

                // TextPart.Text is a convenience property that decodes the content and converts the result to
                // a string for us
                var text = plain.Text;

                File.WriteAllText (Path.Combine (directory, "body.txt"), text);
            }

            // IMessageSummary.HtmlBody is a convenience property that finds the 'text/html' body part for us
            bodyPart = item.HtmlBody;

            if (bodyPart != null) {
                // download the 'text/html' body part

                // Note: In general, you should use `GetBodyPart(item.UniqueId, bodyPart)` instead if you have it available.
                // This particular overload of the GetBodyPart() method exists for convenience purposes where you already
                // know the body-part specifier string before-hand.
                var html = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, bodyPart.PartSpecifier);

                // TextPart.Text is a convenience property that decodes the content and converts the result to
                // a string for us
                var text = html.Text;

                File.WriteAllText (Path.Combine (directory, "body.html"), text);
            }

            // now iterate over all of the attachments and save them to disk
            foreach (var attachment in item.Attachments) {
                // download the attachment just like we did with the body
                var entity = client.Inbox.GetBodyPart (item.UniqueId, attachment);

                // attachments can be either message/rfc822 parts or regular MIME parts
                if (entity is MessagePart) {
                    var rfc822 = (MessagePart) entity;

                    var path = Path.Combine (directory, attachment.PartSpecifier + ".eml");

                    rfc822.Message.WriteTo (path);
                } else {
                    var part = (MimePart) entity;

                    // default to using the sending client's suggested fileName value
                    var fileName = attachment.FileName;

                    if (string.IsNullOrEmpty (fileName)) {
                        // the FileName wasn't defined, so generate one...
                        if (!MimeTypes.TryGetExtension (attachment.ContentType.MimeType, out string extension))
                            extension = ".dat";

                        fileName = Guid.NewGuid ().ToString () + extension;
                    }

                    var path = Path.Combine (directory, fileName);

                    // decode and save the content to a file
                    using (var stream = File.Create (path))
                        part.Content.DecodeTo (stream);
                }
            }
        }

        client.Disconnect (true);
    }
}
See Also