Search code examples
c#gmailimapgmail-imapmailkit

How to delete messages in Gmail (not move to Trash folder) using MailKit


I'm trying to develop an ImapClient using the MailKit library.

How can I permanently remove messages from a Gmail account as opposed to simply moving them to the Trash folder?


Solution

  • On most IMAP servers, the way you would do this is:

    folder.AddFlags (uids, MessageFlags.Deleted, true);
    

    This sets the \Deleted flag on the message(s). The next step would be:

    folder.Expunge (uids);
    

    This would purge the message(s) from the folder.

    Assuming that this does not work on GMail, it's probably because as soon as you add the \Deleted flag to a message on a GMail IMAP server, it moves it to the Trash folder (which is beyond the IMAP client's control).

    Here's an idea that might work, however...

    // First, get the globally unique message id(s) for the message(s).
    var summaries = folder.Fetch (uids, MessageSummaryItems.GMailMessageId);
    
    // Next, mark them for deletion...
    folder.AddFlags (uids, MessageFlags.Deleted, true);
    
    // At this point, the messages have been moved to the Trash folder.
    // So open the Trash folder...
    folder = client.GetFolder (SpecialFolder.Trash);
    folder.Open (FolderAccess.ReadWrite);
    
    // Build a search query for the messages that we just deleted...
    SearchQuery query = null;
    foreach (var message in summaries) {
        var id = SearchQuery.GMailMessageId (message.GMailMessageId);
        query = query != null ? query.Or (id) : id;
    }
    
    // Search the Trash folder for these messages...
    var matches = folder.Search (query);
    
    // Not sure if you need to mark them for deletion again...
    folder.AddFlags (matches, MessageFlags.Deleted, true);
    
    // Now purge them from the Trash folder...
    folder.Expunge (matches);
    

    And you're done...