asp.net-mvc – 与SmtpClient.UseDefaultCredentials属性混淆

在我的MVC4应用程序中,我使用SmtpClient通过Gmail的smtp.gmail.com SMTP服务器发送电子邮件.

我已经使用以下设置配置了我的Web.Config文件

<system.net>
 <mailSettings>
  <smtp deliveryMethod="Network">
   <network enableSsl="true" 
   defaultCredentials="false" 
   host="smtp.gmail.com" 
   port="587" 
   userName="xxMyUserNamexx@gmail.com" 
   password="xxMyPasswordxx" />
  </smtp>
 </mailSettings>
</system.net>

使用SmtpClient并发送电子邮件方法如下所示:

public void SendMail(string fromdisplayName,string fromEmailAddress,string toEmailAddress,string subject,string body)
{
    MailAddress from = new MailAddress(fromEmailAddress,fromdisplayName);
    MailAddress to = new MailAddress(toEmailAddress);
    MailMessage mailMessage = new MailMessage(from,to);
    mailMessage.Body = body;
    mailMessage.Subject = subject;

    SmtpClient client = new SmtpClient();
    //client.UseDefaultCredentials = false;
    client.Send(mailMessage);
}

以上代码按预期工作正常.有什么困扰我的是注释行client.UseDefaultCredentials = false; – 如果我要取消对该行的注释,我将收到一条异常消息,其中指出:

The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication required.

更重要的是,如果我将UseDefaultCredentials属性设置为true或false,我仍然会收到异常消息.避免异常消息的唯一方法是完全删除该行.

这个行为是否正常?你能解释为什么我收到异常消息吗?

解决方法

So why would me explicitly setting the property to false throw an exception?

原因是因为UseDefaultCredentials的setter将Credentials属性设置为null,如果将其设置为false,或者将其设置为CredentialCache.DefaultNetworkCredentials属性(如果设置为true). DefaultNetworkCredentials属性defined by MSDN as

The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running. For a client-side application,these are usually the Windows credentials (user name,password,and domain) of the user running the application. For ASP.NET applications,the default network credentials are the user credentials of the logged-in user,or the user being impersonated.

当您将UseDefaultCredentials设置为true时,它将使用您的IIS用户,并且假设您的IIS用户与您使用的任何SMTP服务器的帐户不具有与您的帐户相同的身份验证凭据.将UseDefaultCredentials设置为false将设置的凭据设置为false.所以无论哪种方式你都会得到这个错误.

以下是使用dotPeek的UseDefaultCredentials设置器:

set
{
    if (this.InCall)
    {
        throw new InvalidOperationException(
            SR.GetString("SmtpInvalidOperationDuringSend"));
    }
    this.transport.Credentials = value 
        ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials 
        : (ICredentialsByHost) null;
  }

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....