Outlook.MailItem有时会失败

时间:2014-12-16 10:10:48

标签: .net outlook

在迭代电子邮件项目时,有时系统无法获取邮件项目,但它会在下次运行时获得相同的电子邮件项目。下面是我用来获取邮件的代码示例。

        var oApplicationClass = new Application();
        NameSpace nameSpace = oApplicationClass.GetNamespace("MAPI");
        Outlook.MAPIFolder inbox = nameSpace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
        Outlook.MAPIFolder deletedItems = nameSpace.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems);

        MailItem mailItem;


        var safeMail = new Redemption.SafeMailItem();
        Items outlookItems = inbox.Items.Restrict("[MessageClass] = \"IPM.Note\"");
        int totalCount = outlookItems.Count;
        string subject = "";
        bool filterMessage = filters.Count > 0;

        if (totalCount > 0)
        {
            for (int i = 1; i <= totalCount; i++)
            {
                outlookItems.Sort("[ReceivedTime]",
                                  sortAscending ? OlSortOrder.olAscending : OlSortOrder.olDescending);

                try
                {
                    mailItem = (MailItem) outlookItems[i];
                    var testCount = mailItem.Attachments.Count;
                    //Code to move the email to deleted items
                }
                catch (Exception oEx)
                {
                    Logger.Debug("Mail item cannot be acquired, continuing to other mail items.");
                    Logger.Debug(oEx.Message);
                    continue;
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

您需要立即释放所有底层COM对象。完成使用后,使用 System.Runtime.InteropServices.Marshal.ReleaseComObject 释放Outlook对象。然后在Visual Basic中将变量设置为Nothing(C#中为null)以释放对该对象的引用。

如果您的加载项尝试枚举存储在Microsoft Exchange Server上的集合中的256个以上的Outlook项目,则这一点尤为重要。如果您未及时发布这些对象,则可以达到Exchange对任何一次打开的最大项目数量的限制。

例如,您可以在How To: Use Restrict method to retrieve Outlook mail items from a folder文章中找到示例代码。