Introduction
Today, I came across a forum post saying, "User is not able to send a mail to his domain that he purchased but able to send mail to the gmail". The actual problem is that gmail wants the clients to be secure even though we set EnableSsl = true;
Simply, it wont work.
To fix the issue, add the RemoteCertificateValidationCallback. Now, it will work fine.
- public class Program
- {
- static void Main(string[] args)
- {
- string senderID = "[email protected]";
- string senderPassword = "xxxx";
- RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;
- string body = "Test";
- try
- {
- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);
- ServicePointManager.Expect100Continue = true;
- MailMessage mail = new MailMessage();
- mail.To.Add("[email protected]");
- mail.From = new MailAddress(senderID);
- mail.Subject = "My Test Email!";
- mail.Body = body;
- mail.IsBodyHtml = true;
- SmtpClient smtp = new SmtpClient();
- smtp.Host = "smtp.gmail.com";
- smtp.Credentials = new System.Net.NetworkCredential(senderID, senderPassword);
- smtp.Port = 587;
- smtp.EnableSsl = true;
- smtp.Send(mail);
- Console.WriteLine("Email Sent Successfully");
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- finally
- {
- ServicePointManager.ServerCertificateValidationCallback = orgCallback;
- }
- }
-
- private static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
- {
- return true;
- }
- }