Search code examples
c#asp.netasp.net-mvc-4exchangewebservices

Handling 401 unauthorised for send email using Exchange EWS


I have the following code that sends emails using Exchange EWS. Everything works fine until the incorrect username and password are supplied and a 401 unauthorised error is returned. I wrapped the send up in a catch statement to handle the error. But the catch statement is not being reached.

public void SendExchangeEmail(EmailModel model, ApplicationUser adminUser) 
{
    var service = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
    {
        Credentials = new WebCredentials(adminUser.Email, adminUser.ExchangePassword),
        TraceEnabled = true,
        TraceFlags = TraceFlags.All,
        Url = new Uri("MyExchangeUrl")
    };

    var email = new EmailMessage(service);
    email.ToRecipients.Add(model.recipient);
    email.Subject = model.Subject;
    email.Body = new MessageBody(model.Body);

    try
    {
        email.Send();
    }
    catch (ServiceResponseException ex)
    {
         // This catch block is not reached when the incorrect username and password are supplied. 
    }
}

What is the correct way to catch the unauthorised error.


Solution

  • Your Exception handling is not correct. "The request failed. The remote server returned an error: (401) Unauthorized. " error throws an ServiceRequestException. Modify your code as:

    try
    {
        email.Send();
    }
    catch (ServiceRequestException ex)
    {
        //Exception handling
    }