title: Using MAPI to access the Exchange Server from a Service
body: <p>I was tasked with building an application that would check email using MAPI. I made use of a <a href="http://www.codeproject.com/Articles/10881/MAPIEx-Extended-MAPI-Wrapper" rel="nofollow">wrapper class</a> coded in cpp, which is accessed from c#. I realize that combining managed and unmanaged code is not necessarily the best path, but it was what I could get to work.</p>
  
  <p>After getting it working, I was asked to make the application a service, so it could be run when the system was not logged in.</p>
  
  <p>The client requires us to use MAPI, and is using Outlook 2007, but I would like it to be compatible with both x86 and x64 architecture. A separate program running on several workstations will be allowed to send mail using a single email address. The service will monitor this account, watching for new email from Exchange saying a message could not be delivered. When this happens, it will make a note in the database for future correction.</p>
  
  <p>My understanding of how Extended MAPI works is that it uses the profile of the person logged in to access the Exchange Server. My question is whether the Exchange Server can be accessed through MAPI when nobody is logged into the system? If this is not possible, does OOM allow for access to a specific email account (or profile) when no user is logged in? Would one method be better than the other when predominantly using c#?</p>
  
  <p>Below is a brief sample of how the wrapper class logs in. I added the second method, but never did get it to log in to a profile other than that of the current user's.</p>
  
  <pre><code>BOOL CMAPIEx::Login(LPCTSTR szProfileName, BOOL bInitAsService)
  {
      DWORD dwFlags=MAPI_EXTENDED | MAPI_USE_DEFAULT | MAPI_NEW_SESSION;
      if(bInitAsService) dwFlags|=MAPI_EXPLICIT_PROFILE | MAPI_NT_SERVICE;
      return (MAPILogonEx(NULL, (LPTSTR)szProfileName, NULL, dwFlags, &amp;m_pSession)==S_OK);
  }
  
  BOOL CMAPIEx::Login(LPCTSTR szProfileName, LPCTSTR szProfilePassword, BOOL bInitAsService)
  {
      DWORD dwFlags=MAPI_EXTENDED | MAPI_EXPLICIT_PROFILE  | MAPI_NEW_SESSION;
      if(bInitAsService) 
          dwFlags|= MAPI_NT_SERVICE;
      return (MAPILogonEx(NULL, (LPTSTR)szProfileName, (LPTSTR)szProfilePassword, dwFlags, &amp;m_pSession)==S_OK);
  }
  </code></pre>
  
  <p>Thank you for any suggestions.</p>