Using asp.net core 3.1 I can send email using this code:
Code snippet 1 using System.Net.Mail.SmtpClient
using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
{
smtp.Host = "mail.my-real-domain-name.com";
smtp.EnableSsl = false;
NetworkCredential credential = new NetworkCredential(emailModel.From,
emailModel.Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = credential;
smtp.Send(mm);
}
but when I try to send email using MailKit it doesn't connect to mailserver
Code snippet 2 in MailKit documentation
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect("mail.my-real-domain-name.com",0,false);
client.Authenticate(emailModel.From, emailModel.Password);
client.Send(message);
client.Disconnect(true);
}
What's the equal of Code snippet 1 using MailKit?
None of below lines worked so I want to know how to send email without specifying port number using MailKit. It doesn't throw any error, just doesn't connect, I mean it stays in client.Connect line.
// client.Connect("mail.my-real-domain-name.com", 465);
// client.Connect("mail.my-real-domain-name.com", 465, true);
// client.Connect("mail.my-real-domain-name.com", 25, false);
// client.Connect("mail.my-real-domain-name.com", 2525, false);
// client.Connect("mail.my-real-domain-name.com", 587,MailKit.Security.SecureSocketOptions.StartTls);
CodePudding user response:
If you take a look at the SmtpClient.cs reference source, in the Initialize() method:
- if port == 0
- if there is a MailConfiguration XML file available, it uses the specified port from the XML (which defaults to port 25): https://referencesource.microsoft.com/#System/net/System/Net/Configuration/SmtpNetworkElement.cs,e4c99455ef3ea37c
- else if there is no XML config file, it uses the static
defaultPortmember, which is set to 25.
So to get the same behavior as System.Net.Mail, use port 25.
MailKit will also accept port = 0 in the Connect() call and, depending on what the SecureSocketOptions argument is, it will choose an appropriate default port in the ComputeDefaultValues() method: https://github.com/jstedfast/MailKit/blob/master/MailKit/Net/Smtp/SmtpClient.cs#L1253
If the port == 0, then if useSsl=true or socketOptions=SslOnConnect, it will choose port 465, otherwise it will choose port 25.
