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!

jstedfast
  • 35,744
  • 5
  • 97
  • 110
BradMcA
  • 339
  • 2
  • 3
  • 10
  • Although you need to download only one message, I have a fully working MailKit example of deleting bulk messages [here](https://github.com/arthurspa/DeleteEmailMessages). To delete a single message is similar. – Arthur Silva Sep 24 '16 at 08:17

1 Answers1

29

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 });
jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • Where do I get those index or uid? Can't find those on the message object. – ygoe Sep 27 '20 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 '20 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 '20 at 07:07
  • 1
    You want the uid because removing messages will change indexes of messages, obviously. – jstedfast Sep 28 '20 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 '20 at 16:04
  • I get AddFlags not a member of iMailfolder. It looks like its a member of iMailfolderExtensions but how do I get that interface? – Brobic Vripiat Oct 13 '22 at 00:08