Why SmtpClient.UseDefaultCredentials is ignored?

Arseni Mourzenko picture Arseni Mourzenko · Jun 6, 2012 · Viewed 21.7k times · Source

I'm trying to send e-mails through a domain SMTP server which uses Integrated Windows Authentication. When explicitly specifying the credentials, everything works fine:

using (var client = new SmtpClient("<Server>"))
{
    client.Credentials = new NetworkCredential("<User name>", "<Password>");
    client.EnableSsl = true;
    client.Send(...);
}

SMTP server logs show EHLO, STARTTLS, STARTTLS and EHLO, then AUTH, MAIL, etc.

When, on the other hand, default credentials are used:

using (var client = new SmtpClient("<Server>"))
{
    client.UseDefaultCredentials = true;
    client.EnableSsl = true;
    client.Send(...);
}
  • the SmtpException is thrown, with a message “Failure sending mail.”;

  • the inner IOException message is: “Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.”, and

  • the inner-inner SocketException is: “An existing connection was forcibly closed by the remote host”.

SMTP server logs show EHLO, STARTTLS, STARTTLS and EHLO, then nothing.

The result is exactly the same (success for the first sample, failure for the second one) if the options are moved from source code to App.config configuration/system.net/mailSettings/smtp/network, and whenever the port number is specified or not.

Given that:

  • according to the documentation, SmtpClient.UseDefaultCredentials “[g]ets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests”, that

  • “For a client-side application, [CredentialCache.DefaultCredentials] are usually the Windows credentials (user name, password, and domain) of the user running the application”, and that

  • the tested code is a Windows Forms client-side application running from the same account whose credentials were specified in the first sample above,

why the second sample fails, while the first one works?


On a forum it was suggested that the issue may be cause by SMTP server not supporting NTLM. By EHLOing the server, it appears that NTLM is supported, one of the response lines being 250-AUTH GSSAPI NTLM.

Answer

Gen1-1 picture Gen1-1 · Aug 23, 2017

If UseDefaultCredentials is set to true, it does NOT mean use the values in the Credentials property. Instead, it means use the credentials of the "currently logged on user", which in the case of IIS web apps will usually be the app pool identity, and in the case of a Windows service is the identity of the service, and in the case of a desktop application, it's the identity of the user logged into Windows.

See the Microsoft document (https://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials(v=vs.110).aspx) where it states that if UseDefaultCredentials is false (the default) and you don't provide anything in the Credentials property, "then mail is sent to the server anonymously".