Search code examples
c#-4.0.net-4.0vstooutlook-addinmailitem

Get parent mail item to read headers when message is forwarded or replied to


I want to read the mail item headers to look for a specific value when an item is replied to or forwarded. If the value is found in the headers we will then take some action. The code below will trap the Forward event but it does not give me the parent message that contains all the typical header data. Instead it traps a new message based on the parent that has no header data. This makes sense since it has yet to be sent.

I have also attempted do the same thing with the Application.ItemSend event, to trap when the user clicks the send button. Unfortunately, I still can't figure out how to access the parent message.

My question is, is there another event or another process that we need to use to capture the parent when a user hits the reply or forward button or a better wat to go about this entirely?

Thanks in advance for your assistance!

private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            _activeExplorer = Application.Explorers[1];
            _activeExplorer.SelectionChange += _activeExplorer_SelectionChange;
        }

private void _activeExplorer_SelectionChange()
        {
            Selection selection = Application.ActiveExplorer().Selection;
            if (selection != null && selection.Count == 1 && selection[1] is MailItem)
            {
               MailItem selectedMail = selection[1] as MailItem;
               ((Outlook.ItemEvents_10_Event)selectedMail).Forward += mailItem_Forward;
            }
        }

private void mailItem_Forward(object Forward, ref bool Cancel)
        {
            if (Forward != null)
            {
                if (Forward is Outlook.MailItem)
                {
                    Outlook.MailItem mailItem = Forward as Outlook.MailItem;
                    mailItem.Save();
                    String EmailHeader = mailItem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E");
    
                    // The string is always null because this is a new message , need to access the parent of the forward...how? 
                    if (EmailHeader.Contains("X-Key-Classification") == true)
                    {
                        Debug.WriteLine(EmailHeader);
                    }
                }

            }
        }

Solution

  • But MailItem.Forward event fires on a particular item, so you do know what that parent message is. If you use the same callback for multiple items, you can create a wrapper for the MailItem object with the object stored in a property and the event handler beign a method on that wrapper object - this way you will know which item raised the event.