简体   繁体   中英

Download attachments according to number in subject (MailKit library)

I'm downloading attachments from e-mail with this code:

int count = client.Count();
List<MimeMessage> allMessages = new List<MimeMessage>(count);
for (int i = 0; i < count; i++)
{
    allMessages.Add(client.GetMessage(i));
    foreach (var attachment in allMessages[i].Attachments)
    {
        using (var stream = File.Create(AppDomain.CurrentDomain.BaseDirectory + "/folderForSegments/" + attachment.ContentType.Name))
        {
            if (attachment is MessagePart)
            {
                var part = (MessagePart)attachment;
                part.Message.WriteTo(stream);
            }
            else
            {
                var part = (MimePart)attachment;
                part.ContentObject.DecodeTo(stream);
            }
        }
    }
}

It works perfect but I want download attachments in sequence, according to number in subject . For example: if my inbox looks like this

在此处输入图片说明 attachments will be saved on my disc in order: 6, 8, 7, 3, 2... I want save attachments in order: 1, 2, 3, 4, 5... How can I do this?

For POP3, there's no way to download the messages in that order without knowing ahead of time what order the messages were in on the server.

If order is more important than wasted bandwidth, you could download the headers first using client.GetHeader(i) for each message so that you can use the Subject header value to determine the order, but that's a lot of wasted bandwidth because you'd just end up downloading the message headers a second time when you downloaded the messages.

Another option is to download all of the messages, add them to a List<T> and then sort them based on Subject before iterating over the messages and saving the attachments, but this might use too much RAM depending on how large your messages are.

Edit:

For IMAP, assuming your server supports the SORT extension, you can do something like this:

if (client.Capabilities.HasFlag (ImapCapabilities.Sort)) {
    var query = SearchQuery.SubjectContains ("damian_mistrz_");
    var orderBy = new OrderBy[] { OrderBy.Subject };
    foreach (var uid in folder.Sort (query, orderBy) {
        var message = folder.GetMessage (uid);

        // save attachments...
    }
}

If your server does not support SORT, then you could probably do something like this:

var query = SearchQuery.SubjectContains ("damian_mistrz_");
var orderBy = new OrderBy[] { OrderBy.Subject };
var uids = folder.Search (query);
var items = folder.Fetch (uids, MessageSummaryItems.Envelope | MessageSummaryItems.UniqueId);

items.Sort (orderBy);

foreach (var item in items) {
    var message  = folder.GetMessage (item.UniqueId);

    // save the attachments...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM