首页 > 解决方案 > 通过 C#、Exchange 和 EWS 托管 API 发送电子邮件会出现错误 407:请求失败 - 需要代理身份验证。为什么?

问题描述

我正在为我在一家公司工作的客户编写基于C#EWS 托管 API 2.2.0 (Microsoft.Exchange.WebServices.dll 程序集)的 Windows 窗体应用程序。

该应用程序的逻辑很简单:我的客户将他的电子邮件地址“sender@ABC.domain.com”和收件人的电子邮件地址“recipient@contoso.com”和应用程序发送一个基于 HTML 的电子邮件到接受者。

该应用程序必须连接到我的客户公司的 Exchange 服务器,将我的客户身份验证到 Exchange 作为 Windows 域用户(使用 Windows 域身份验证)(客户端已经使用他的用户名“发件人”登录到 Windows,并且此 Windows 用户发出请求) 然后,通过他的邮箱“sender@ABC.domain.com”发送电子邮件。

到目前为止,我已经编写了上面的代码,这似乎是正确的,但它给了我这个错误:“请求失败。远程服务器返回错误:(407)。需要代理身份验证”

    try{

        //Initialize and bound 'service' to the latest known version of Exchange
        ExchangeService service = new ExchangeService();

        //Use the Windows logged-in user domain account credentials:
        //Is this correct / is this enough???
        service.UseDefaultCredentials = true;

        ServicePointManager.ServerCertificateValidationCallback = myValidationCallBackFunction;

        service.AutodiscoverUrl("sender@ABC.domain.com", myRedirectionCallback);
        MessageBox.Show("Autodiscover Exchange URL found:" + service.Url.ToString());

        //Impersonation test - just in case - but this is not make any difference in the error
        service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "sender@ABC.domain.com");

        //Initialize and set an EmailMessage
        EmailMessage message = new EmailMessage(service);
        message.Subject = "HelloWorld";

        string emailMessageBody = "<!DOCTYPE html><html> ... </html>";

        message.Body = new MessageBody(BodyType.HTML, emailMessageBody);
        email.ToRecipients.Add("recipient@contoso.com");

        message.SendAndSaveCopy();

        MessageBox.Show("E-Mail sent successfully");

    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }

我的客户使用 Windows 10。他的 PC 是 Windows 域的一部分,其 url 为“XYZ.domain.com”,他在 Windows 上的用户名是“sender”。他还在他的 PC 中安装了一个 Outlook 应用程序,该应用程序可以完美地连接到他公司网络上的 Exchange Server...

我完全是 Windows 域帐户/身份验证的业余爱好者。这是 Windows 域身份验证问题吗?这是 Exchange 连接设置问题吗?或者问题出在身份验证部分的代码中(我是否需要添加更多内容)?

标签: c#exchange-serverexchangewebservicesews-managed-apiwindowsdomainaccount

解决方案


我自己找到了部分解决方案!

现在我的代码工作正常。

问题出在我客户端 PC 上 Windows 10 的代理设置中。出于某种原因,他启用了手动代理设置,但他不知道。当我找到它并禁用它时,电子邮件发送正常。

我说我找到了解决方案的“一部分”,因为:

1) Outlook 365 在本地 Exchange Server 2010 上运行良好,即使我是否启用了代理设置。但我的应用程序仅适用于禁用代理设置。有谁知道这是怎么解释的?为什么 Outlook 在这两种方式下都能正常工作?

2) 如果我的客户公司的 IT 强制他一直启用代理设置,我该如何绕过这个错误?我是否必须以某种方式传递用户的凭据(带或不带密码)?如果是,那么我该如何使用 C# 来做到这一点?


推荐阅读