加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:58:34 所属栏目:asp.Net 来源:网络整理
导读:在我的MVC4应用程序中,我使用SmtpClient通过Gmail的smtp.gmail.com SMTP服务器发送电子邮件. 我已经使用以下设置配置了我的Web.Config文件: system.net mailSettings smtp deliveryMethod="Network" network enableSsl="true" defaultCredentials="false" h
在我的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;
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读