Click or drag to resize
MimeKit

IMailFolderGetStreamAsync(UniqueId, BodyPart, CancellationToken, ITransferProgress) Method

Asynchronously get a body part as a stream.

Namespace: MailKit
Assembly: MailKit (in MailKit.dll) Version: 4.7.1
Syntax
C#
Task<Stream> GetStreamAsync(
	UniqueId uid,
	BodyPart part,
	CancellationToken cancellationToken = default,
	ITransferProgress progress = null
)

Parameters

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

Return Value

TaskStream
The body part stream.
Remarks
Asynchronously gets a body part as a stream.
Example
C#
public static void CacheBodyParts (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);

            // now iterate over all of the body parts and save them to disk
            foreach (var bodyPart in item.BodyParts) {
                // cache the raw body part MIME just like we did with the body
                using (var stream = client.Inbox.GetStream (item.UniqueId, bodyPart)) {
                    var path = Path.Combine (directory, bodyPart.PartSpecifier);

                    using (var output = File.Create (path))
                        stream.CopyTo (output);
                }
            }
        }

        client.Disconnect (true);
    }
}
See Also