简体   繁体   English

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

[英]Handling 401 unauthorised for send email using Exchange EWS

I have the following code that sends emails using Exchange EWS. 我有以下代码使用Exchange EWS发送电子邮件。 Everything works fine until the incorrect username and password are supplied and a 401 unauthorised error is returned. 在提供错误的用户名和密码并返回401未经授权的错误之前,一切工作正常。 I wrapped the send up in a catch statement to handle the error. 我将发送包裹在catch语句中以处理错误。 But the catch statement is not being reached. 但是没有达到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. 
    }
}

What is the correct way to catch the unauthorised error. 捕获未授权错误的正确方法是什么。

Your Exception handling is not correct. 您的异常处理不正确。 "The request failed. The remote server returned an error: (401) Unauthorized. " error throws an ServiceRequestException. “请求失败。远程服务器返回错误:(401)未经授权。”错误引发ServiceRequestException。 Modify your code as: 将您的代码修改为:

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

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

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. 电子邮件用户的权限仅在Outlook应用程序中有效。 If the command is called outside it is blocked, hence the need for the permission that your Exchange admin knows. 如果在外部调用该命令,则会阻止该命令,因此需要您的Exchange管理员知道的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM