Search code examples
vb.netoutlookvstooutlook-addinoffice-addins

Outlook VSTO Add-in VB - How to read the subject line of an email opened in the inbox?


I have created an add-in that allows a user to add information concerning an email into a SQL Table.

I am currently trying to implement a quality-of-life feature that will read the subject line of an opened email from the inbox into the relevant field of the user form. I have tried several methods and have had no success.

This is what I have currently:

Dim newMail As Outlook.MailItem
Dim oInspector As Outlook.Inspector

oInspector = Microsoft.Office.Interop.Outlook.Application.ActiveInspector()
newMail = oInspector.CurrentItem

[Initializing other parts of form]

   If oInspector Is Nothing Then
      MsgBox("No Active Inspector")
   Else
      newMail = oInspector.CurrentItem
      With AddEmailSubjectTextBox
           .Text = newMail.Subject
      End With
   End If

Besides the "reference to a non-shared member requires an object reference" error that is thrown, I believe part of my issue is that the ActiveInspector method and CurrentItem are supposed to represent an email that is being written in a pop-up window and has yet to be sent.


Solution

  • The following line of code should deal with a valid Outlook Application instance:

    oInspector = Microsoft.Office.Interop.Outlook.Application.ActiveInspector()
    

    But you are trying to call a method on a type declaration. In the VBA environment you can use the global Application property. For example:

    oInspector = Application.ActiveInspector()
    

    In VSTO based add-ins you can use the Application property of the ThisAddin class. You may also use the Globals namespace which gives access to the Application instance anywhere in the code of your add-in, see Global access to objects in Office projects for more information. For VSTO add-ins the code should look like that:

    Dim newMail As Outlook.MailItem
    Dim oInspector As Outlook.Inspector
    
    oInspector = Globals.ThisAddIn.Application.ActiveInspector()
    newMail = oInspector.CurrentItem
    
    [Initializing other parts of form]
    
       If oInspector Is Nothing Then
          MsgBox("No Active Inspector")
       Else
          newMail = oInspector.CurrentItem
          With AddEmailSubjectTextBox
               .Text = newMail.Subject
          End With
       End If
    

    Be aware, the item opened in the inspector window can be different - appointment, task, note, document. So, it also makes sense to add a check for the item type opened in the inspector window.

    Finally, if you need to get the currently selected item in the Explorer window, you need to use the Selection property