通过UID进行MailKit IMAP搜索并下载各个MIME部分

时间:2017-10-27 23:20:59

标签: c# imap mailkit

我已经能够检索到我检查过的最后一条消息之后的 UID 列表,因此我可以从IMAP服务器获取新消息

using(var client = new ImapClient())
{
   //client authentication code...

   var inbox = client.Inbox;
   inbox.Open(FolderAccess.ReadOnly);

   //msgIdx contains the UID of the last message I've checked,
   // so I can retrieve all the new messages after this one.
    var range = new UniqueIdRange(new UniqueId((uint) msgIdx), UniqueId.MaxValue);


    IList<UniqueId> uids = inbox.Search(range, SearchQuery.All);
    foreach(var uid in uids)
    {
       //With the following instruction I download the whole message...
       var message = inbox.GetMessage(uid);
       LblMessageLog.Text += uid + " Subject:" + message.Subject + " []<br/>";
    }
    client.Disconnect(true);
}

问题在于我不想下载整个邮件,但只有特定的附件,因为我知道它将始终存在于所有邮件中。

MailKit网站上有一个例子,但它与我上面的搜索有冲突:

foreach (var summary in inbox.Fetch (0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure)) {
    if (summary.Body is BodyPartMultipart) {
        var multipart = (BodyPartMultipart) summary.Body;

        var attachment = multipart.BodyParts.OfType<BodyPartBasic> ().FirstOrDefault (x => x.FileName == "cert.xml");
        if (attachment != null) {
            // this will download *just* the attachment
            var part = inbox.GetBodyPart (summary.UniqueId, attachment);
        }
    }
}

如何在UID上执行过滤数据的两个流程,然后仅下载部分的电子邮件?

1 个答案:

答案 0 :(得分:0)

这里是如何混合两者:

var range = new UniqueIdRange(new UniqueId((uint) msgIdx),    UniqueId.MaxValue);

var items = inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope);
foreach(var item in items)
{
    LblMessage.Text += item.UniqueId + " Subject:" + item.Envelope.Subject + "<br/>";
}

Fetch方法有一个重载接受一个唯一ID的IList