Depending on your email host provider settings, it's easy to set host name, port number and SSL feature to sending mail by using corresponding properties in SmtpClient
:
SmtpClient smtp = new SmtpClient(hostserver);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential(MailID, Password);
smtp.Host = hostserver; // host name as mail server
smtp.Port = Convert.ToInt32(portno); // some hosts doesn't support port 25 for SMTPS, try this port instead or use 587
smtp.EnableSsl = true; // use SSL configuration
smtp.Send(mail);
Update (Explicit & Implicit SSL)
Keep in mind that System.Net.Mail.SmtpClient
only supports explicit SSL, which requires insecure connection to SMTP server over port 25 to negotiate with TLS. There is SMTP over SSL for port 465 which requires TLS negotiation before connection to SMTP server established, but still doesn't support implicit SSL with standard System.Net.Mail
library. The reason is explained at this reference.
There is no way to use Implicit SSL (SMTPS) with System.Net.Mail
.
Implicit SSL would have the entire connection is wrapped in an SSL
layer. A specific port would be used (port 465 is common). There is
no formal RFC covering Implicit SSL.
Implicit SSL would go something like: Start SSL (start encryption)
-> Connect -> Authenticate -> send data
This is not considered a bug, it’s by design. There are two types of
SSL authentication for SMTP, and we only support one with
System.Net.Mail (by design) – Explicit SSL.
To use implicit SSL, you need to utilize libraries which enables CDOSYS, such like System.Web.Mail.MailMessage
and System.Web.Mail.SmtpMail
(which seems to be obsolete but works with both explicit and implicit SSL, require CDO configuration schemas to work):
System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
mail.To = emailid;
mail.Bcc = AdminEmail;
mail.From = new MailAddress(MailID);
mail.Subject = Subject;
mail.Body = Body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", hostServer);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", MailID);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", Password);
System.Web.Mail.SmtpMail.SmtpServer = hostServer;
System.Web.Mail.SmtpMail.Send(mail);
Related issue:
How can I send emails through SSL SMTP with the .NET Framework?