You can try to remove the UID , which should be more reliable and unique for each message. It worked well for me in the past.
Edit:. When deleting a message, all indexes are shifted by one, you can use two separate counters. One to keep track of when you iterated through the entire block (messagesLeft), and the other will keep track of the current index of the message, which will be reduced by 1 if the message is deleted (as it will move one place on the line).
Mailbox box = client.AllMailboxes["inbox"]; Fetch fetch = box.Fetch; int messagesLeft = box.Count; int msgIndex = 0; while (messagesLeft > 0) { msgIndex++; messagesLeft--; Message email = fetch.MessageObject(msgIndex); if (criteria) { box.UidDeleteMessage(fetch.Uid(msgIndex), true); msgIndex--; } }
In response to your comment, here is a more complete example of how you can use the UID to delete without worrying about the numeric position / index.
class Email { int UID { get; set; } DateTime Sent { get; set; } public string Body { get; set; } // put whichever properties you will need } List<Email> GetEmails(string mailbox); { Mailbox box = client.AllMailboxes[mailbox]; Fetch fetch = box.Fetch; List<Email> list = new List<Email>(); for (int x = 1; x <= box.MessageCount; x++) { Message msg = fetch.MessageObject(x); list.Add(new Email() { }
source share