调用sendmail()方法时抛出Null Reference Exception

时间:2016-08-26 13:19:54

标签: c# office-interop nullreferenceexception

我正在修改我为工作编写的帮助台程序,并希望重构我的代码,以便在收到故障单后,它会先尝试发送电子邮件,然后再在我的数据库中创建故障单。< / p>

但是如果我在我的context.CreateTicket(ticket)方法之前调用我的SendMail(ticket)方法,我得到一个空引用。异常,即使我事先声明并初始化票证对象。

这是我的NewTicket方法的代码

private void CreateNewTicket()
    {
        //set search filter to currentuser
        dS.Filter = "(&(objectClass=user)(anr=" + userName + "))";

        //find current user in the acrive director
        SearchResult sR = dS.FindOne();

        var ticket = new HelpTicket
        {
            Title = title,
            DescText = descText,
            Employee = GetProp(sR, "Name"),
            EmpEmail = GetProp(sR, "mail"),
            DateSubmited = DateTime.Now,
            // Urgency = selectedUrgency,
            UrgentID = SelectedUrgency.UrgentID,
            TypeID = SelectedProblemType.TypeID

        };

        try
        {
            //if sendmail here it thorws the exception
            //SendMail(ticket);
            try {
                context.CreateTicket(ticket);
                //If I call context.createticket first it works  
                SendMail(ticket);
                CloseDialog = true;
            }
            catch
            (System.Exception ex )
            {
                MessageBox.Show("Error Submitting ticket: " + ex.Message,"Error Submitting Ticket",MessageBoxButton.OK,MessageBoxImage.Error);
            }

        }
        catch (Exception ex1)
        {
            MessageBox.Show("Error Submitting ticket, please try again.\n" + ex1.Message,"Error Creating ticket",MessageBoxButton.OK,MessageBoxImage.Error);
            CloseDialog = true;
        }

    }

SendMail(票证)代码

 public override void SendMail(HelpTicket ticket)
    {
        Microsoft.Office.Interop.Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();

        Microsoft.Office.Interop.Outlook.MailItem mailMsg =
        (Microsoft.Office.Interop.Outlook.MailItem)outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
        Microsoft.Office.Interop.Outlook.Inspector oInspector = mailMsg.GetInspector;
        mailMsg.To = "myhelpticketemail@mycompany.com";
        mailMsg.Subject = ticket.Title;
        mailMsg.HTMLBody = "<b>Urgency: </b>" + ticket.Urgency.Description + "<br/>" +
            "<b>Problem Type: </b>" + ticket.ProblemType.ProblemDesc + "<br/><hr/><br/>" +
               ConvertToHtml(ticket.DescText);
        mailMsg.Send();

    }

如果您需要更多代码段,请告知我们并发布

1 个答案:

答案 0 :(得分:0)

在SendMail中

您正在推荐Ticket的对象属性,但您确实如此 没有创建它们或你没有显示它们。无论如何基于您发布的代码 只要您引用ticket.ProblemType.ProblemDesc和ticket.Urgency.Description 你将获得null引用异常。