Search code examples
c#.net.net-coresmtppostfix-mta

SmtpClient fails under .NET Framework but succeeds under .NET Core


We're running a Postfix SMTP server and we have a very simple C# application connecting to it.

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("... sender address ...", "... sender name ...", System.Text.Encoding.UTF8);
msg.To.Add(new MailAddress("... my address ..."));

msg.Subject = "This is a test Subject";
msg.Body = "This is a test Message";

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("... postfix mail server domain ...");
System.Net.NetworkCredential creds = new System.Net.NetworkCredential()
{
    UserName = "... username ...",
    Password = "... password ..."
};

smtp.EnableSsl = true;
smtp.Credentials = creds;
smtp.UseDefaultCredentials = false;
smtp.Port = 587;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
smtp.Send(msg);

The application runs successfully when the target platform is any .NET Core framework - specifically we are using .NET 6.0.

The application fails when the target platform is any .NET Framework - specifically we are using .NET Framework 4.8.

The error message is:

{ "Transaction failed. The server response was: 5.7.1 <c-xx-xxx-xxx-xx.xxx.xx.comcast.net[xx.xx.xx.xx]>: Client host rejected: Access denied" }

Comparing POSTFIX Logs for both running applications shows a similar "connection" attempt except in the failing app the 3rd Log line looks like:

NOQUEUE: reject: RCPT from c-xx-xxx-xxx-xx.xxx.xx.comcast.net[xx.xx.xx.xx]: 554 5.7.1 c-xx-xxx-xxx-xx.xxx.xx.comcast.net[xx.xx.xx.xx] Client host rejected: Access denied; from=<...> to=<...> proto=ESMTP helo=<DESKTOP...>

The successful 3rd line looks like:

64AB1603889 client=c-xx-xxx-xxx-xx.xxx.xx.comcast.net[xx.xx.xx.xx], sasl_method=CRAM-MD5. sasl_username=... username ...

It looks to me like the .NET Framework version of the app is failing to send credentials for logging in.

Has anyone experienced this happening between different .NET frameworks and have an idea of what could fix this?


Solution

  • This is why I don't have any hair...

    I was able to get the script to work by swapping 2 lines of code.

    By changing:

    smtp.Credentials = creds;
    smtp.UseDefaultCredentials = false;
    

    To:

    smtp.UseDefaultCredentials = false;
    smtp.Credentials = creds;
    

    Now the application can send mail in both Core and .Net Framework. I guess setting the UseDefaultCredentials afterward was overwriting the value in the .NET Framework.

    Anyway, hopefully that nightmare helps someone else out someday.