Search code examples
c#imapmailkit

Mailkit stream lots of messages and delete them


I want to export gmail messages into files, message per file. What is the best strategy for this?

for (int i = 0; i < inbox.Count; i++)
   {
        var message = inbox.GetMessage(i);
        // export message
        inbox.AddFlags (i, MessageFlags.Deleted);
   }

My concern is if I delete message inside the loop, won't it disrupt the the order indexes. I cannot use 2 separate loops for reading and deleting, because gmail is slow to read and if reading loop fails at some point, then I have to start the whole process all over again.


Solution

  • With standard IMAP servers, setting the \Deleted flag on a message does not remove the message from the folder, it simply sets a flag which a future EXPUNGE command will use to decide which messages to purge.

    That said, servers like GMail use non-standard behavior by default and so your concern is valid.

    To avoid this type of problem, I would recommend using uids instead. I highly recommend avoiding the use of index based API's altogether.

    var uids = folder.Search (SearchQuery.All);
    foreach (var uid in uids) {
        var message = folder.GetMessage (uid);
        folder.AddFlags (uid, MessageFlags.Deleted);
    }