Search code examples
c#smtpcredentialssmtpclient

Why SmtpClient.UseDefaultCredentials is ignored?


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.


Solution

  • I think you actually have to specify the Credentials as well. The UseDefaultCredentials is mere a flag telling the SMTPClient to use the Credentials provided to the Credentials property.

    client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
    

    Here's some other things to try: