Outlook电子邮件搜索崩溃

时间:2019-10-28 10:48:44

标签: c# winforms outlook

我正在处理获取列表的代码,并检查项目是否在电子邮件主题中,我试图遍历所有电子邮件以与列表进行比较,但是该程序在190封左右电子邮件后崩溃(有289个电子邮件)文件夹中的电子邮件)

我在线搜索了此问题的解决方案,但对我没有任何帮助

oApp = new Microsoft.Office.Interop.Outlook.Application();

        // Get the MAPI namespace.
        oNS = oApp.GetNamespace("mapi");

        // Log on by using the default profile or existing session (no dialog box).
        oNS.Logon(Missing.Value, Missing.Value, false, true);

        // Alternate logon method that uses a specific profile name.
        // TODO: If you use this logon method, specify the correct profile name
        // and comment the previous Logon line.
        //oNS.Logon("profilename",Missing.Value,false,true);

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

        //Get the Items collection in the Inbox folder.
        oItems = oInbox.Items;
        MessageBox.Show(oItems.Count+"");
        oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetLast();
public void SearchEmail()
        {
            if (counter<oItems.Count)
            {
                try
                {
                    string s;

                    if (oMsg != null)
                    {
                        s = oMsg.Subject;



                        for (int i = 0; i < allTickets.Count; i++)
                        {
                            label2.Text = oMsg.Subject;
                            string ticketID = allTickets[i].ToString();
                            if (s.Contains(ticketID) && oMsg.UnRead)
                            {
                                unreadTickets.Add(ticketID);
                            }
                        }
                    }

                        oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oItems.GetPrevious();

                        counter++;
                        button2.Text = counter + "";




                }

                //Error handler.
                catch (Exception x)
                {
                     //MessageBox.Show(x.ToString());
                }
            }
        }

catch异常给了我这个

无法将类型为“ system .__ comobject”的com对象转换为接口类型为“ microsoft.office.interop.outlook”

然后我得到这个错误:

nullreferenceexception对象引用未设置为对象的实例

1 个答案:

答案 0 :(得分:0)

请记住,收件箱可以包含MailItemReportItemMeetingItem以外的其他项目。那可以解释转换错误。您需要将项目视为通用对象,并使用反射读取Class属性(所有OOM对象都公开)-如果它是43(olMailItem),则可以将其强制转换为MailItem 。或者,您可以使用“ as”运算符并检查是否为空。

还请记住,除非您首先调用Items.Sort并指定排序顺序,否则Items集合不会以任何特定顺序排序。否则,您不确定从Items.GetLast获得的收益。