我正在使用此处的代码使用 MailKit 从邮件中下载附件。在检索附件的 foreach 循环中,它始终返回空。因为它是空的,所以它没有进入 foreach 循环。如果我做错了什么,请纠正我。
var messages = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId);
int unnamed = 0;
foreach (var message in messages)
{
var multipart = message.Body as BodyPartMultipart;
var basic = message.Body as BodyPartBasic;
if (multipart != null)
{
//Here the attachments is always empty even though my mail has email with attachements
var attachments = multipart.BodyParts.OfType<BodyPartBasic>().Where(x => x.IsAttachment);
foreach (var attachment in attachments)
{
var mime = (MimePart)client.Inbox.GetBodyPart(message.UniqueId.Value, attachment);
var fileName = mime.FileName;
if (string.IsNullOrEmpty(fileName))
fileName = string.Format("unnamed-{0}", ++unnamed);
using (var stream = File.Create(fileName))
mime.ContentObject.DecodeTo(stream);
}
}
else if (basic != null && basic.IsAttachment)
{
var mime = (MimePart)client.Inbox.GetBodyPart(message.UniqueId.Value, basic);
var fileName = mime.FileName;
if (string.IsNullOrEmpty(fileName))
fileName = string.Format("unnamed-{0}", ++unnamed);
using (var stream = File.Create(fileName))
mime.ContentObject.DecodeTo(stream);
}
}