使用Exchange EWS处理401未经授权发送电子邮件

时间:2018-09-06 07:26:28

标签: c# asp.net asp.net-mvc-4 exchangewebservices

我有以下代码可以使用Exchange EWS发送电子邮件。在提供错误的用户名和密码并返回401未经授权的错误之前,一切工作正常。我将发送包裹在catch语句中以处理错误。但是没有达到catch语句。

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. 
    }
}

捕获未授权错误的正确方法是什么。

2 个答案:

答案 0 :(得分:2)

您的异常处理不正确。 “请求失败。远程服务器返回错误:(401)未经授权。”错误引发ServiceRequestException。将您的代码修改为:

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

答案 1 :(得分:0)

您需要与您的Exchange管理员联系,以允许服务帐户(AD帐户)获得在Outlook应用程序外部发送电子邮件的权限(我忘记了角色/权限的特定名称)。

然后修改您的代码以使用以下内容:

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);

电子邮件用户的权限仅在Outlook应用程序中有效。如果在外部调用该命令,则会被阻止,因此需要您的Exchange管理员知道的权限。