Sending mail using SmtpClient in .net

前端 未结 5 1494
一整个雨季
一整个雨季 2021-02-07 02:19

I am unable to send the mail using smtp client. here is the code:

SmtpClient client=new SmtpClient(\"Host\");
client.Credentials=new NetworkCredential(\"username         


        
5条回答
  •  再見小時候
    2021-02-07 02:35

    I figured out that setting the SmtpClient Credentials property before setting the ' UseDefaultCredentials = false ' UseDefaultCredentials = false causes the credentials to be ignored.

    Fails:

    SmtpClient smtp = new SmtpClient;
    smtp.Credentials = new NetworkCredential("user","pass");
    smtp.UseDefaultCredentials = false;
    

    Works:

    SmtpClient smtp = new SmtpClient;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("user","pass");
    

    Go figure.

    ** UPDATE **

    The reason the order is important here is that the setter on the UseDefaultCredentials property actually sets the Credentials to null via the decompiled code:

    /// Gets or sets a  value that controls whether the  are sent with requests.
    /// 
    ///  if the default credentials are used; otherwise . The default value is .
    /// You cannot change the value of this property when an e-mail is being sent.
    public bool UseDefaultCredentials
    {
      get
      {
        return this.transport.Credentials is SystemNetworkCredential;
      }
      set
      {
        if (this.InCall)
          throw new InvalidOperationException(SR.GetString("SmtpInvalidOperationDuringSend"));
        this.transport.Credentials = value ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials : (ICredentialsByHost) null;
      }
    }
    

提交回复
热议问题