Search code examples
c#mailkit

How can I delete an email using MailKit?


How can I delete an email using MailKit version 4.3.0?

Here is the code that Im using:

...
//Ensure that the inbox folder is open
if (!Inbox.IsOpen)
{
    //Here never enters
    Inbox.Open(FolderAccess.ReadWrite);
}

//Delete message from inbox
try
{
    //Here is where I get the exception
    Inbox.AddFlags(uid, MessageFlags.Deleted, true);
    Inbox.Expunge();
}
catch (Exception ex)
{
    //Console.WriteLine($"Error al intentar borrar el correo con UID {uid}: {ex.Message}");
}
finally
{
    //Close inbox folder after deleting message
    if (Inbox.IsOpen)
    {
        Inbox.Close();
    }
}
...

When Im debugging the code it throws me the next exception: MailKit.FolderNotOpenException: 'The folder is not currently open in read-write mode.'

I asked ChatGPT about the exception and told me that I can use the following code to open in read-write mode but Visual Studio says that the property IsWritable does not existe:

if (!Inbox.IsOpen || !Inbox.IsWritable)
{
    Inbox.Open(FolderAccess.ReadWrite);
}

How can I achieve this?


Solution

  • The inbox is initially opened in read only mode. In order to delete messages, you have to reopen it again, but this time in read write mode. So, just get rid of that if (!Inbox.IsOpen) and always open it:

    Inbox.Open(FolderAccess.ReadWrite);
    
    Inbox.AddFlags(uid, MessageFlags.Deleted, true);
    Inbox.Expunge();