我发现在设置“ UseDefaultCredentials = false ”之前设置 SmtpClient Credentials 属性UseDefaultCredentials = false
会导致凭据被忽略。
失败:
SmtpClient smtp = new SmtpClient;
smtp.Credentials = new NetworkCredential("user","pass");
smtp.UseDefaultCredentials = false;
作品:
SmtpClient smtp = new SmtpClient;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("user","pass");
去搞清楚。
** 更新 **
顺序在这里很重要的原因是属性上的设置器实际上UseDefaultCredentials
通过反编译的代码将 设置为:Credentials
null
/// <summary>Gets or sets a <see cref="T:System.Boolean" /> value that controls whether the <see cref="P:System.Net.CredentialCache.DefaultCredentials" /> are sent with requests.</summary>
/// <returns>
/// <see langword="true" /> if the default credentials are used; otherwise <see langword="false" />. The default value is <see langword="false" />.</returns>
/// <exception cref="T:System.InvalidOperationException">You cannot change the value of this property when an e-mail is being sent.</exception>
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;
}
}