I’m working on an email application for my university assignment and running into problems with Google’s SMTP service. My C# code works fine with other email providers but fails when trying to connect to Gmail’s servers. I think the issue might be related to SSL certificate validation but I’m not sure how to fix it.
var mailSender = new SmtpClient("smtp.gmail.com", 587);
mailSender.EnableSsl = true;
mailSender.UseDefaultCredentials = false;
mailSender.Credentials = new NetworkCredential("myuser", "mypass");
try
{
var email = new MailMessage();
email.To.Add("[email protected]");
email.From = new MailAddress("[email protected]");
email.Subject = "Hello World";
email.Body = "This is a test message";
mailSender.Send(email);
email.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("Email failed: " + ex.Message);
}
The error mentions SSL authentication problems and certificate chain issues. Has anyone encountered this before and knows what might be causing it?
Google changed their SMTP authentication; regular Gmail passwords don’t work anymore. You need to use App Passwords now. Start by going to your Google Account settings, enable 2FA, and then create an App Password for your application. Substitute your regular password with this 16-character App Password in the NetworkCredential. I faced the same issue in my university project last semester, and this method solved it. The SSL error can be misleading because Google terminates the connection before the SSL handshake if the credentials are incorrect.
Hold up - you using the right TLS version? Gmail needs TLS 1.2 or higher, and .NET defaults don’t always match. Try adding ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; before creating your SmtpClient. Also check if your uni’s blocking port 587 - lots of schools block outbound SMTP for security.
This SSL certificate issue usually happens when certificate chain validation fails on certain networks or dev environments. I ran into the same thing on a corporate project where our internal network was messing with Gmail’s certificate verification.
Before you bypass certificates, check if your system’s certificate store is up to date and make sure no corporate firewalls are intercepting SSL traffic. Try running your app from a different network to test this.
If certificate validation is really broken in your dev setup, you can add a custom certificate validation callback that allows Gmail’s certificates while keeping other connections secure. Just make sure you understand the security risks before doing this, especially if it’s going to production.