0 votes

Hi i am using your code to delete my emails . ( my account is gmail). emails are deleted from inbox but in my mac email client they are not deleted. when i delete from my email client it deletes emails both from inbox and of course from every other email client i have this account. do you have any suggestions. (it is like my mail client is not synced with the mailbox correctly or i am not deleting them in the proper way)

by (790 points)

1 Answer

+1 vote

If you want to delete a message from all Gmail folders using IMAP:

  • Move it to the [Gmail]/Trash folder.
  • Delete it from the [Gmail]/Trash folder.

Use CommonFolders class to get actual folder names (it may be different in localized Gmail's versions)

All emails in [Gmail]/Spam and [Gmail]/Trash are deleted after 30 days. If you delete a message from [Gmail]/Spam or [Gmail]/Trash, it will be deleted permanently.

This is the code:

using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.UseBestLogin("user@gmail.com", "password");

    // Recognize Trash folder
    List<FolderInfo> folders = imap.GetFolders();
    CommonFolders common = new CommonFolders(folders);
    FolderInfo trash = common.Trash;

    // Find all emails we want to delete
    imap.SelectInbox();
    List<long> uids = imap.Search(Expression.Subject("email to delete"));

    // Move email to Trash
    List<long> uidsInTrash = new List<long>();
    foreach (long uid in uids)
    {
        long uidInTrash = (long)imap.MoveByUID(uid, trash);
        uidsInTrash.Add(uidInTrash);
    }

    // Delete moved emails from Trash
    imap.Select(trash);
    foreach (long uid in uidsInTrash)
    {
        imap.DeleteMessageByUID(uid);
    }

    imap.Close();
}

https://www.limilabs.com/blog/delete-email-permanently-in-gmail

by (297k points)
...