Search code examples
c#outlookconsole-applicationmarshallingoffice-interop

Problems accessing Outlook from c# Application


I'm writing a console application, which checks the contents of an outlook mailbox, in order to read the contents of specific emails into a database.

This application works fine within Visual studio, whether or not Outlook is open.

If I build the application and run it from the exe it only works when Outlook is open, which isn't really a problem.

However, I need to run it from a scheduled task as it has to run every few minutes. This will not work at all.

I'm using the following code:

System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("OUTLOOK");

int collCount = processes.Length;

if (collCount != 0)
{
    OutlookApp = Marshal.GetActiveObject("Outlook.Application") as Application;  
}
else
{
    OutlookApp = new Application();
} 

The error message I'm getting is:

System.Runtime.InteropServices.COMException (0x800401E3): Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))
at System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, IntPtr reserved, Object& ppunk) at System.Runtime.InteropServices.Marshal.GetActiveObject(String progID) at ImportCruiseEmails.Program.Main()

On the line :

Marshal.GetActiveObject("Outlook.Application") as Application;

Both Outlook and the console application are running under my user account, which has administrator permissions. I've been pulling my hair out with this all afternoon. Can anybody please shed any light on it? Cheers!


Solution

  • Even through the user accounts are the same, security contexts are different since the scheduler runs as a service. And no Office app can be used in a service.

    Your options are

    1. In case of an Exchange Server, use EWS to access the mailbox.

    2. Extended MAPI (C++ or Delphi only)

    3. Redemption (I am its author, any language) - it wraps Extended MAPI and its RDO family of objects can be used from a service.