Search code examples
c#moveoutlook-addinmailitem

Outlook plugin move mail item is slow


I'm working on a plugin for outlook that moves emails to a folder. Is working fine but looks like the move method of MailItem is slow take 4-5 seconds to move 10 emails I'm using something like

for (int i = folder.Items.Count; i > 0; i--)
{
     Outlook.MailItem mi = (Outlook.MailItem)theRootFolder.Items[i];
     if (mi != null)
     {            
              mi.Move(destFolder);         
     }

Solution

  • Don't use multipls dots in the single line of code:

     folder.Items.Count
    

    Break the chain of property and method calls and declare each call on a separate line of code. Thus, you will be able to release underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. This is particularly important if your add-in attempts to enumerate more than 256 Outlook items in a collection that is stored on a Microsoft Exchange Server. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. Read more about that in the Systematically Releasing Objects article in MSDN.

    Be aware, the Move method of the MailItem class returns an object which should be released after.