developing an outlook 2007 addin with c# - retrieving the mailitem.Body property RRS feed

  • Question

  • I am working on an Outlook addin using c#.  I am more or less just trying different things to see how it all works.  I first wanted to get some fields from an email written and sent in outlook.  So I can get the To, CC, and subject with the following code, but when I try to get mailItem.Body or mailItem.HTMLBody I get an exception:

    System.Runtime.InteropServices.COMException was unhandled by user code
      Message=The operation failed.
      Source=Microsoft Office Outlook
           at Microsoft.Office.Interop.Outlook._MailItem.set_Body(String Body)
           at FirstOutlookPlugin.ThisAddIn.Inspectors_NewInspector(Inspector Inspector) in L:\Pub. Files\Beginning Visual C# 2008\Chapter09\List try\FirstOutlookPlugin\FirstOutlookPlugin\ThisAddIn.cs:line 25

    Does anyone know what's up?  I have read it may be something to do with security patches and SMIME (which I am trying to read up on).  Seems like if it works getting the "to" field and stuff, it should be no problem getting the body also. 

    Thanks for any help!!

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml.Linq;
    using Office = Microsoft.Office.Core;
    using Outlook = Microsoft.Office.Interop.Outlook;
    namespace FirstOutlookPlugin
        public partial class ThisAddIn
            private void ThisAddIn_Startup(object sender, System.EventArgs e)
           this.Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
            private void Application_ItemSend(object Item, ref bool Cancel)
                Outlook.MailItem mail1 = Item as Outlook.MailItem;
                string address = mail1.Recipients[1].Address;
                string subject = mail1.Subject;
                string body = mail1.Body;
                MessageBox.Show("Hello, you send an email to " + address );
    MessageBox.Show("Hello, you email said " + body);

    • Moved by Bob Shen Wednesday, April 25, 2012 5:41 AM (From:Visual C# General)
    Tuesday, April 24, 2012 3:29 AM

All replies

  • Outlook.MailItem mail1 is one email or all? How do you differentiate that?



    Tuesday, April 24, 2012 4:11 AM
  • Sorry, I should have clarified.  My intention is to have the user open a new e-mail in outlook, and "capture" the email if it's addressed to a certain address.  Then "forward" a copy of that email to other addresses.  So mail1 is the "open" email in the outlook new mail editor.  It all works, except for the body, throws that error. 

    I am doing it this way to learn the ins and outs of outlook programming.  I admit it may be easier (but I don't know yet) to capture the email as a whole (.msg ??) and then forward, as opposed to copying the body, creating a new email programatically, then sending.

    Tuesday, April 24, 2012 3:48 PM
  • from stack trace of exception we can see that some code that you did not presented us here is trying to set mail's Body. Are you sure that you get exception on body's retrieval?

    as for other ideas - you can try using 'Copy' method on mailItem which creates a copy (suprise suprise) or you can call SaveAs to save msg and later call OpenSharedItem to open it.

    Wednesday, April 25, 2012 9:05 AM
  • This is the whole code.  I am typing some text in the body, just as I type some into the "To", and "subject".    I am going to try your two suggestions, see what I can come up with.   I can't figure why the body would be any different than the "to" or "subject".  The error comes up on the  string body = mail1.Body;


    Messing around, without trying to "get" the body using  

    string body = mail1.Body

    I look at the mail1 in the locals, and it's showing this in the body and htmlbody property

    Body {System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: The operation failed.
       --- End of inner exception stack trace ---
       at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
       at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
       at System.Dynamic.IDispatchComObject.GetMembers(IEnumerable`1 names)} System.Reflection.TargetInvocationException

    • Edited by pdgrimm Thursday, April 26, 2012 1:48 AM
    Wednesday, April 25, 2012 10:26 PM
  • what does bodyformat show?
    Thursday, April 26, 2012 7:05 AM
  • Hi,

    I believe Damian referred to this part in the stack trace:

    at FirstOutlookPlugin.ThisAddIn.Inspectors_NewInspector(Inspector Inspector)

    Do you have an older version in which you handled the NewInspector Event?
    In this case it might be still running.

    Have you try to run the Add-in in debug and see on which line it breaks?


    Thursday, April 26, 2012 8:49 AM
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml.Linq;
    using Office = Microsoft.Office.Core;
    using Outlook = Microsoft.Office.Interop.Outlook;
    namespace FirstOutlookPlugin
        public partial class ThisAddIn
            //Outlook.Inspectors inspectors;
            Outlook.MailItem mailItem;
            //private void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
            //    Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
            //    if (mailItem != null)
            //    {
            //        if (mailItem.EntryID == null)
            //        {
            //            //mailItem.Subject = "This text was added by using code";
            //            ////  mailItem.Body = "This text was added by using code";
            //            //mailItem.CC = "";
            //            //MessageBox.Show("Hello, you want to send an email!");
            //        }
            //    }
            private void ThisAddIn_Startup(object sender, System.EventArgs e)
                //inspectors = this.Application.Inspectors;
                //inspectors.NewInspector +=
                //new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
                this.Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
            private void Application_ItemSend(object Item, ref bool Cancel)
                Outlook.MailItem mail1 = Item as Outlook.MailItem;
                string address = mail1.Recipients[1].Address;
                string body = mail1.HTMLBody;
                MessageBox.Show("Hello, the email body you sent it  " + body);
            private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
            #region VSTO generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InternalStartup()
                this.Startup += new System.EventHandler(ThisAddIn_Startup);
                this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
            #endregion VSTO generated code

    • Edited by pdgrimm Sunday, April 29, 2012 1:51 AM
    Sunday, April 29, 2012 1:40 AM
  • Sunday, April 29, 2012 1:54 AM
  • do you have latest fixes for outlook installed? SP3 at least? What is your outlook version?
    Monday, April 30, 2012 8:01 AM
  • I've found this, maybe it can help:

    (I assume that removing all other code from Item_Send and simply reading the body still throws an exception, right?)

    Thursday, May 3, 2012 2:58 PM
  • Yeah, without all the code, it still throws the error.

    Friday, May 11, 2012 3:38 AM

  • I have noticed that this works when I am replying to an email from a certain website (which is confusing as heck).  The Header info from the email I reply to and it works is:

    Return-Path: <>
    Received: from ([*****])
              by with ESMTP
              id <>
              for <>; Sun, 13 May 2012 17:04:35 +0000
    Return-Path: <>
    Authentication-Results:  *******************************************************
    X-Authority-Analysis: v=2.0 cv=ae7jbGUt c=1 sm=0 a=3AfMCnJ3Bo0A:10 a=05ChyHeVI94A:10 a=IkcTkHD0fZMA:10 a=ayC55rCoAAAA:8 a=EM-kevoCAAAA:8 a=lu_OINDs35tX6rF4LOMA:9 a=KuebM_UyKYVGx4LFciIA:7 a=QEXdDO2ut3YA:10 a=ubDoIFd-qspV3_rt:21 a=BuvQda8ZKevti_LW:21 a=wr5NEAjvuvr11g+8dhRX1A==:117
    X-Cloudmark-Score: 0
    Received: from [**] ([**] helo=hrndva-web24-z02)
    by (envelope-from <>)
    (ecelerity r()) with ESMTPA
    id B8/F5-11677-3A9EFAF4; Sun, 13 May 2012 17:04:35 +0000
    Message-ID: <20120513170435.ACRTJ.13669.root@hrndva-web24-z02>
    Date: Sun, 13 May 2012 13:04:35 -0400
    From:  <>
    To: "Pride Grimm Jr." <>
    Subject: RE: Question Re: Item 839733 in R/C Marketplace
    In-Reply-To: <002201cd30c5$0b299ee0$217cdca0$>
    MIME-Version: 1.0
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: 7bit
    X-Priority: 3 (Normal)
    Sensitivity: Normal
    X-Brightmail-Tracker: AAAAAA==
    X-Brightmail-Tracker: AAAAAA==

    And the header of a reply that doesn't work (which is sent from my email to my email) and produces the error

    Return-path: <>
    Delivery-date: Sun, 13 May 2012 17:43:52 -0500
    Received: from ([**)
    by with esmtp (Exim 4.69)
    (envelope-from <>)
    id 1SThW4-0003F6-PL
    for; Sun, 13 May 2012 17:43:52 -0500
    X-Authority-Analysis: v=2.0 cv=D8PF24tj c=1 sm=0 a=ntejTMcob8pcWcfhO/5VFw==:17 a=8kesQlGQzRAA:10 a=05ChyHeVI94A:10 a=yMhMjlubAAAA:8 a=SSmOFEACAAAA:8 a=nS36O97Bj3wUElCrIrAA:9 a=pDXWthBxvaoA:10 a=gKO2Hq4RSVkA:10 a=UiCQ7L4-1S4A:10 a=hTZeC7Yk6K0A:10 a=ntejTMcob8pcWcfhO/5VFw==:117
    X-Cloudmark-Score: 0
    X-Originating-IP: **
    Received: from [*] ([*] helo=PridePC)
    by (envelope-from <>)
    (ecelerity r()) with ESMTP
    id 32/5E-13336-82930BF4; Sun, 13 May 2012 22:43:52 +0000
    From: "Pride Grimm Jr." <>
    To: <>
    Subject: test
    Date: Sun, 13 May 2012 18:43:48 -0400
    Message-ID: <000001cd3159$dd1391b0$973ab510$>
    MIME-Version: 1.0
    Content-Type: multipart/alternative;
    X-Mailer: Microsoft Office Outlook 12.0
    Thread-Index: Ac0xWdyt4NGUriNZQ3WVNAISV33Yrg==
    Content-Language: en-us
    X-Brightmail-Tracker: AAAAAQAAAlk=

    I'm thinking is has something to do with what a guy is talking about here:

    But I can't figure it out.

    • Edited by pdgrimm Friday, May 18, 2012 2:47 AM
    Monday, May 14, 2012 12:32 AM

  • I can't believe this isn't simpler.  Could this be caused by a security patch?  

    Wednesday, May 16, 2012 11:28 PM
  • I can't see how this email can be showing encrypted.

    I changed the code to make sure the message format for my test emails.  They are definatly  IPM.Note



    Wednesday, May 16, 2012 11:29 PM
  • Is there anyway to read the body of a smime email?  Convert it?  Stop outlook from using it?
    • Edited by pdgrimm Thursday, May 31, 2012 1:24 AM
    Wednesday, May 30, 2012 8:24 PM
  • normally when you get handled mailitem from outlook/vsto (or mail is selected) it is already decoded/converted by outlook and looks like normal mail. Just for clarification - what do you mean by body of smime email? original encrypted or a decrypted one?
    Thursday, May 31, 2012 9:04 AM
  • It's actually the body of the outgoing email in the ItemSend event.  I don't have my outlook set to s/mime.  It says the body type is ipm.note, but throws the error.
    Saturday, June 2, 2012 10:28 PM
  • i do not think that outgoing email in itemsend event is already encrypted.
    Sunday, June 3, 2012 4:56 AM
  • What else can be causing it?

    Here is the innerexception


    • Edited by pdgrimm Wednesday, June 6, 2012 1:09 AM
    Wednesday, June 6, 2012 1:08 AM
  • disable _all_ add-ins beside yours. Try only reading item.body in itemsend event (not setting). Does it still fail?
    Wednesday, June 6, 2012 8:22 AM