创建新mailitem的ItemAdd事件处理程序中的Outlook VSTO始终具有null wordeditor

时间:2015-12-22 18:22:05

标签: c# outlook vsto

我尝试创建一个处理特定MailItem的Outlook加载项,并将结果转发给另一组人。为了进行处理,我相信我需要使用WordEditor才能获得正确的格式,但是当我尝试访问该对象时,它返回null。当我无法访问WordEditor时,我能够正确地发送邮件,所以我可能忽视了一些简单的事情。如何为这个新的MailItem访问WordEditor?

    Outlook.NameSpace outlookNameSpace;
    Outlook.MAPIFolder inbox;
    Outlook.Items items;
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        outlookNameSpace = this.Application.GetNamespace("MAPI");
        inbox = outlookNameSpace.GetDefaultFolder(
                Microsoft.Office.Interop.Outlook.
                OlDefaultFolders.olFolderInbox);

        items = inbox.Items;
        items.ItemAdd +=
            new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);

    }

    void items_ItemAdd(object Item)
   {
        string filter = "Filter";
        if (Item is Outlook.MailItem)
        {
            Outlook.MailItem mail = (Outlook.MailItem)Item;
            if (Item != null)
            {
                if (mail.MessageClass == "IPM.Note" &&
                           mail.Subject.ToUpper().Contains(filter.ToUpper())
                           && mail.Attachments.Count == 1)
                {

                    Outlook.Attachments attachments = mail.Attachments;
                    if (attachments != null)
                    {

                        Outlook.Attachment file = attachments[1];
                        //Process attachment...
                        Outlook.MailItem newMail = this.Application.CreateItem(Outlook.OlItemType.olMailItem);
                        Outlook.Inspector insp = newMail.GetInspector;
                        insp.Activate();
                        newMail.Subject = "Subject";
                        newMail.To = "email@example.com";
                        Word.Document emailBody = insp.WordEditor as Word.Document;
                        //emailBody is always null
                        newMail.Send();                          

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(newMail);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(file);
                    }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(attachments);
                }
            }
         System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);

        }
    }

1 个答案:

答案 0 :(得分:0)

在不使用Inspector对象和Word对象模型的情况下适当设置MailIten.HTMLBody