Reputation: 321
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.
Upvotes: 0
Views: 1535
Reputation: 36
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
}
Upvotes: 2
Reputation: 1079
You need to talk to your Exchange Administrator to allow a service account (AD Account) for the permission to send email outside the outlook application (I forgot the specific name for the role / permission).
Then modify your code to use the following:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new System.Net.NetworkCredential(serviceAccount.UserName, serviceAccount.Password); service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, userEmail); service.AutodiscoverUrl(userEmail, RedirectionUrlValidationCallback);
The permission of the user of the email only works inside outlook application. If the command is called outside it is blocked, hence the need for the permission that your Exchange admin knows.
Upvotes: 0