Home > Enterprise >  How To Delete Multiple Emails From Gmail Using Mailkit?
How To Delete Multiple Emails From Gmail Using Mailkit?

Time:12-15

I am able to delete a single email using Mailkit. But when I am trying to delete multiple emails at a time then I get error "cannot convert from 'System.Collections.Generic.List' to 'MailKit.UniqueId'". Actually, I have all email's UniqueId which I have stored in List. ex: List uniqueIdList = new List() { 45901, 45902, 45903 };

public async Task BulkDeleteEmailAsync()
{
    try
    {
        List<long> uniqueIdList = new List<long>() { 45901, 45902, 45903 };
        SaslMechanismOAuth2 oauth2 = await Authentication();
        using (var client = new ImapClient())
        {
            await client.ConnectAsync("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);
            await client.AuthenticateAsync(oauth2);
            IMailFolder folder = client.GetFolder("INBOX");
            folder.Open(FolderAccess.ReadWrite);

            if (!folder.IsOpen == true)
                throw new Exception($"{folder.FullName} is not open.");

            folder.AddFlags(uniqueIdList, MessageFlags.Deleted, false); //here is Error
            folder.Expunge(uniqueIdList, CancellationToken.None); //here is Error
            
            folder.Close();
            await client.DisconnectAsync(true);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

CodePudding user response:

From the Documentation here for the AddFlags and for the UniqueId ctor, You may just modifying the init of the list like the following.

For C# 9.0

IList<UniqueId> uniqueIdList = new List<UniqueId>() { new(45901), new(45902), new(45903) };

For older versions

IList<UniqueId> uniqueIdList = new List<UniqueId>() { new UniqueId(45901), new UniqueId(45902), new UniqueId(45903) };

I could find this is getting compiled but could not verify the output though through Fiddle.

Hope this helps!

  • Related