Search code examples
c#outlookvsto

Outlook VSTO - How to intercept an email at the time of its closure


I am writing some code to intercept a user and prompt them to do something when certain conditions are not met. My issue is that I am expecting the user to close the email by clicking the x in the top right hand corner. I am listening for this by using the

Outlook.ItemEvents_10_CloseEventHandler

basic code:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        public Outlook.MailItem OriginalMailItem
        ((Outlook.ItemEvents_10_Event)OriginalMailItem).Close += new Outlook.ItemEvents_10_CloseEventHandler(Item_Close);
    }

the function:

void Item_Close(ref bool Cancel)
    {
    // Do something with the OriginalMailItem here
        private Outlook.MAPIFolder workersavefolder = ohaworker.Inbox.Folders[ohaworker.WorkerJobFolderName];
        Outlook.MailItem workerMailItem = OriginalMailItem.Move(workersavefolder);
    }

I am unable to do anything here with the target email given the following error:

'The item's properties and methods cannot be used inside this event procedure.'

I think the basic reason is probably because the email is about to close. My questions is - is there any other way I can still grab this email after closure and do something with it?

My initial though was that I might grab the EntryID or Conversation ID and then somehow grab the email via another means, but I cant seem to find anything to connect to so that I can continue the code. Comments and feedback welcomed!

Thankyou


Solution

  • Yes, you can reopen the item by its entry id later when you are out of the event handler. You can use either a Timer (use the one from the Forms namespace as it runs on the main thread) or use Dispatcher.CurrentDispatcher.InvokeAsync()