Search code examples
c#outlookcomexception

C# Outlook COMException "Item has been moved or deleted"


When running this loop to delete multiple of the same email I run into this exception. I believe it has to do with the length of oItems losing 1 due to an item being deleted, but it is not updated in the foreach loop.

            //Get the Inbox folder.
            Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            //Get the Items collection in the Inbox folder.
            Outlook.Items oItems = oInbox.Items;

                //loops through all inbox items
                foreach (object item in oItems)
                {
                    //checks to only use MailItems (no MeetingItems etc.)
                    if (item is Outlook.MailItem)
                    {
                        if (item.Subject != null)
                        {
                            if (item.SenderEmailAddress == "no-reply@virginpulse.com")
                            {
                                item.Delete();
                            }
                        }
                    }
                }

Solution

  • Do not use "foreach" when modifying a collection by calling Move or Delete.

    Use a down "for" loop

    for(int i = oItems.Count; i >= 1; i--)
    {
      object item = oItems[i];
      ...