Confused with the SmtpClient.UseDefaultCredentials Property
So why would me explicitly setting the property to false throw an exception?
The reason for this is because the setter for UseDefaultCredentials
sets the Credentials
property to null if you set it to false, or it sets it to the CredentialCache.DefaultNetworkCredentials
property if set to true. The DefaultNetworkCredentials
property is 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.
When you set UseDefaultCredentials
to true, it's using your IIS user, and I'm assuming that your IIS user does not have the same authentication credentials as your account for whatever SMTP server you're using. Setting UseDefaultCredentials
to false null's out the credentials that are set. So either way you're getting that error.
Here's a look at the setter for UseDefaultCredentials
using dotPeek:
set
{
if (this.InCall)
{
throw new InvalidOperationException(
SR.GetString("SmtpInvalidOperationDuringSend"));
}
this.transport.Credentials = value
? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials
: (ICredentialsByHost) null;
}
I was getting the same message and it was driving me crazy. After reading this thread I realized that the order mattered on setting my credentials. This worked:
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(smtpSettings.Username, smtpSettings.Password);
While this generated the error you describe:
client.Credentials = new NetworkCredential(smtpSettings.Username, smtpSettings.Password);
client.UseDefaultCredentials = false;
This is just an FYI to anybody else having the same problem.