Sasha Sasha - 1 month ago 40
C# Question

5.7.0 User not authenticated in asp.net core1 with mailkit and strato server

In asp.net core 1 app I'm trying to send email with mailkit library(version 1.8.1) to strato server. My code:

var emailMessage = new MimeKit.MimeMessage();
try
{
emailMessage.From.Add(new MimeKit.MailboxAddress("Support", "some@test.com"));
emailMessage.To.Add(new MimeKit.MailboxAddress("", "test@test.com"));
emailMessage.Subject = "Subject";
var bodyBuilder = new MimeKit.BodyBuilder();
bodyBuilder.HtmlBody = @"<b>Some body</b>";

emailMessage.Body = bodyBuilder.ToMessageBody();

using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Timeout = 15000;
// Accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;

await client.ConnectAsync("smtp.strato.de", 587, MailKit.Security.SecureSocketOptions.Auto);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");

// Note: only needed if the SMTP server requires authentication
await client.AuthenticateAsync(login, passord);

await client.SendAsync(emailMesage);//here error!
await client.DisconnectAsync(true);
}
return true;
}
catch (System.Exception)
{
return false;
}


When I'm trying to send email I get 5.7.0 User not authenticated error, despite authentication passed. The same code, for example, with gmail works fine.

Any ideas how to fix it?

Answer

The problem is that smtp.strato.de resets its authentication state when the SMTP client sends an EHLO command after authenticating, even though the specifications strongly suggest that the client should do that.

In other words, smtp.strato.de is broken.

That said, you can work around this by doing the following:

client.QueryCapabilitiesAfterAuthenticating = false;

As long as you set that property to false before authenticating, it will work.