Search code examples
c#imapmailkit

MailKit IMAP search by UID and download individual MIME parts


I've been able to retrieve the list of UIDs that come after the last one message I've checked, so I can get from the IMAP server only the new messages:

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);
}

The problem is that I don't want to download the whole message, but only a specific attachment, as I know it will exist always, in all messages.

There is an example on the MailKit website but it goes in conflict with the search I do above:

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);
        }
    }
}

How can I do both processes of filtering data on UID and then download only a part of the email message?


Solution

  • here is how to mix the two:

    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 method has an overload accepting an IList of UniqueIDs