15

I am using MailKit (https://github.com/jstedfast/MailKit) to connect to google apps via imap, how can I delete a single message though ? (I am fine to have it moved to trash, just need it out of the inbox.

So far I have it connected, downloading, parsing links from message bodies. I just need this one last action to have what I need.

Thanks!

1
  • Although you need to download only one message, I have a fully working MailKit example of deleting bulk messages here. To delete a single message is similar. Sep 24, 2016 at 8:17

1 Answer 1

30

To delete a message from a folder on the IMAP server, this is all you need to do:

client.Inbox.AddFlags (new int[] { index }, MessageFlags.Deleted);

or

client.Inbox.AddFlags (new UniqueId[] { uid }, MessageFlags.Deleted);

Now the message is marked as \Deleted on the server.

You can then purge the folder of all deleted items by calling:

client.Inbox.Expunge ();

If you are using UIDs instead of indexes and the IMAP server supports the UIDPLUS extension (check the client.Capabilities), you can expunge just a selected set of messages like this:

if (client.Capabilities.HasFlag (ImapCapabilities.UidPlus))
    client.Inbox.Expunge (new UniqueId[] { uid });
6
  • Where do I get those index or uid? Can't find those on the message object.
    – ygoe
    Sep 27, 2020 at 14:44
  • for (int index = 0; index < folder.Count; index++) ... is an index. UIDs can be gotten from a folder.Search() query or from a folder.Fetch() if you request the MessageSummaryItems.UniqueId.
    – jstedfast
    Sep 27, 2020 at 15:04
  • Thanks, but how stable is that index? When new messages arrive or a message is removed (in my session or another), will the index change? Thinking of how foreach is invalid after modifying the iterated collection.
    – ygoe
    Sep 28, 2020 at 7:07
  • 1
    You want the uid because removing messages will change indexes of messages, obviously.
    – jstedfast
    Sep 28, 2020 at 11:11
  • 1
    Since it sounds like you are downloading all messages as if the IMAP server was a POP3 server, you can do this:var uids = folder.Search (SearchQuery.All); foreach (var uid in uids) message = folder.GetMessage(uid);
    – jstedfast
    Sep 28, 2020 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.