Friday, July 01, 2011

C# SMTP email sending code

When I tested this code in webapplication its works fine.But my webmail server is HTTPS based and I wanted to integrate this into my SharePoint webpart.

In this case,set EnableSsl true on your smtp object and specify the port number if you are not using the SMTP's default port 25.

Still you got an error use the below code to off the Certificate Validation while relying on HTTP.
If you are an developer and testing it on the PC where you installed "fiddler".Just make sure its Off.
Use the below line just before to Send method.
 System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; 
            MailMessage mail = new MailMessage();
            SmtpClient smtp = new SmtpClient("webmail smtp");

            mail.From = new MailAddress("");

            mail.Subject = "Subject";
            mail.Body = "Email contents";

            smtp.Credentials = new System.Net.NetworkCredential("userid", "pwd");
            smtp.EnableSsl = true;

            Response.Write("Sent !");
        catch (Exception ex)