I am using MailKit (version 1.18.0) and getting below error while connecting to SMTP Office 365.
SmtpClient client = new SmtpClient();
Connect Method:
client.Connect("smtp.Office365.com", 587, true);
Error Message: "The handshake failed due to an unexpected packet format"
I searched on the web for this scenario and found that for few people, it got resolve by using useSSL false value. So then I tried passing false for useSSL but got invalid remote certificate error.
client.Connect("smtp.Office365.com", 587, false);
Error Message: "The remote certificate is invalid according to the validation procedure."
After researching again, found that we should tried different overload method for connect with start TLS.
client.Connect("smtp.Office365.com", 587, SecureSocketOptions.StartTls);
Error Message: "The remote certificate is invalid according to the validation procedure."
If I run the below powershell from the same server, it's working fine. It's sending email without an issue.
$emailFrom = "[email protected]"
$emailto = "[email protected]"
$Subject = "Test SMTP"
$Body = "Test from Server"
$SMTPServer = "smtp.office365.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SMTPServer, 587)
$SMTPClient.enablessl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
I tried above things on port 25 as well but got same issues. This issue is occurring only for smtp.Office365.com host using MailKit. Any help or suggestions would be greatly appreciated.