Forum Discussion

RoyMGiv's avatar
RoyMGiv
Copper Contributor
Jun 05, 2024

Unable to initialize ExchangeService instance

I am trying to write a program that checks for changes in a mailbox's calendar every time it runs and updates a database. My problem begins at the very top of the assignment when I initialize the  ExchangeService instance and any function I try to run on it returns 

 

 

 

The request failed. The remote server returned an error: (401) .

 

 

 

 I initialized it like this: 

 

 

 

 private static void initExchangeService()
 {
     m_ExchangeService = new ExchangeService();
     m_ExchangeService.UseDefaultCredentials = true;
     m_ExchangeService.KeepAlive = true;

     string domain = ConfigurationManager.AppSettings["Domain"];
     m_ExchangeService.Credentials = new System.Net.NetworkCredential(CREATOR_MAIL, CREATOR_PASSWORD, domain);
     m_ExchangeService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, CREATOR_MAIL);
     if (string.IsNullOrEmpty(EXCHANGE_URL))
     {
         m_ExchangeService.AutodiscoverUrl(CREATOR_MAIL);
     }
     else
     {
         m_ExchangeService.Url = new Uri(EXCHANGE_URL);
     }

     writeToLog($"Initialized exchange service for {CREATOR_MAIL}", MESSAGE);
 }

 

 

 

The mailbox I am trying to access has 2-step authentication disabled and I worked with the system admin to ensure on our end that I have the permissions I need to run this but any address I try (even non real ones) returns the same error.

 

I'd love some help figuring out what the problem is.

  • The 401 error suggests an authentication issue. Check the following:

    Ensure CREATOR_MAIL and CREATOR_PASSWORD are correct.
    Set UseDefaultCredentials to false.
    Confirm the EXCHANGE_URL is correct or use AutodiscoverUrl with a valid callback.
    Verify you have the necessary permissions for impersonation.
    Here's a refined initialization:

    csharp
    Copy code
    private static void initExchangeService()
    {
    m_ExchangeService = new ExchangeService();
    m_ExchangeService.UseDefaultCredentials = false;
    m_ExchangeService.KeepAlive = true;

    string domain = ConfigurationManager.AppSettings["Domain"];
    m_ExchangeService.Credentials = new System.Net.NetworkCredential(CREATOR_MAIL, CREATOR_PASSWORD, domain);
    m_ExchangeService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, CREATOR_MAIL);
    m_ExchangeService.Url = string.IsNullOrEmpty(EXCHANGE_URL) ? new Uri(EXCHANGE_URL) : m_ExchangeService.AutodiscoverUrl(CREATOR_MAIL);

    writeToLog($"Initialized exchange service for {CREATOR_MAIL}", MESSAGE);
    }
    Ensure the network allows the connection and there's no firewall blocking it.

Resources