| ImapFolderGetBodyPartAsync(UniqueId, BodyPart, CancellationToken, ITransferProgress) Method |
Asynchronously get the specified body part.
Namespace: MailKit.Net.ImapAssembly: MailKit (in MailKit.dll) Version: 4.7.1
Syntax Exceptions Remarks
Gets the specified body part.
Example 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);
var query = SearchQuery.SubjectContains ("MimeKit").Or (SearchQuery.SubjectContains ("MailKit"));
var uids = client.Inbox.Search (query);
var items = client.Inbox.Fetch (uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
foreach (var item in items) {
var directory = Path.Combine (baseDirectory, item.UniqueId.ToString ());
Directory.CreateDirectory (directory);
var bodyPart = item.TextBody;
if (bodyPart != null) {
var plain = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, bodyPart);
var text = plain.Text;
File.WriteAllText (Path.Combine (directory, "body.txt"), text);
}
bodyPart = item.HtmlBody;
if (bodyPart != null) {
var html = (TextPart) client.Inbox.GetBodyPart (item.UniqueId, bodyPart);
var text = html.Text;
File.WriteAllText (Path.Combine (directory, "body.html"), text);
}
foreach (var attachment in item.Attachments) {
var entity = client.Inbox.GetBodyPart (item.UniqueId, attachment);
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;
var fileName = attachment.FileName;
if (string.IsNullOrEmpty (fileName)) {
if (!MimeTypes.TryGetExtension (attachment.ContentType.MimeType, out string extension))
extension = ".dat";
fileName = Guid.NewGuid ().ToString () + extension;
}
var path = Path.Combine (directory, fileName);
using (var stream = File.Create (path))
part.Content.DecodeTo (stream);
}
}
}
client.Disconnect (true);
}
}
See Also