Delete email messages with IMAP
This article describes how to delete email messages using Mail.dll .NET IMAP library and IMAP protocol.
Internally deleted messages are flagged with \DELETED flag and are actually deleted after the client issues EXPUNGE command. Mail.dll issues this command automatically.
Following code will find unique ids of all unseen messages in the Inbox folder and delete them one by one.
// C# using Limilabs.Client.IMAP; using Limilabs.Mail; using System; using System.Collections.Generic; class Program { static void Main(string[] args) { using (Imap imap = new Imap()) { imap.Connect("imap.example.com"); // use ConnectSSL for SSL. imap.Login("user", "password"); imap.SelectInbox(); List<long> uids = imap.Search(Flag.Unseen); foreach (long uid in uids) { imap.DeleteMessageByUID(uid); } imap.Close(); } } };
' VB.NET Imports Limilabs.Mail Imports Limilabs.Client.IMAP Imports System Imports System.Collections.Generic Public Module Module1 Public Sub Main(ByVal args As String()) Using imap As New Imap() imap.Connect("imap.example.com") ' use ConnectSSL for SSL. imap.Login("user", "password") imap.SelectInbox() Dim uids As List(Of Long) = imap.Search(Flag.Unseen) For Each uid As Long In uids imap.DeleteMessageByUID(uid) Next imap.Close() End Using End Sub End Module
You can also use bulk delete methods, which are much faster when operating on large number of unique ids. This is because EXPUNGE command is issued only once.
// C# using (Imap imap = new Imap()) { imap.Connect("imap.example.com"); // use ConnectSSL for SSL. imap.Login("user", "password"); imap.SelectInbox(); List<long> uids = imap.Search(Flag.Unseen); imap.DeleteMessageByUID(uids); imap.Close(); }
' VB.NET Public Module Module1 Public Sub Main(ByVal args As String()) Using imap As New Imap() imap.Connect("imap.example.com") ' use ConnectSSL for SSL. imap.Login("user", "password") imap.SelectInbox() Dim uids As List(Of Long) = imap.Search(Flag.Unseen) imap.DeleteMessageByUID(uids) imap.Close() End Using End Sub End Module
Gmail server behaves a bit differently than most IMAP server please read the delete emails from Gmail for details.