HttpRequestException with SSL certificate validation failure when calling Gmail API in C#

I’m having trouble with my C# application that uses the Gmail API. Everything runs smoothly for several hours, but then I get a random SSL certificate error.

var gmailClient = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = userCredential,
    ApplicationName = AppName,
});

var response = gmailClient.Users.Messages.Send(emailMessage, "me").Execute();

The error happens at the Execute() method:

System.Net.Http.HttpRequestException: An error occurred while sending the request. 
---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. 
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

The only way to fix it is by restarting my app or rebooting the computer. After that, it works perfectly again. How can I prevent this from happening and handle it properly in my code?

It seems you’re encountering a certificate caching issue. The Gmail API client might be holding onto expired or invalid certificates. Instead of restarting your application, consider recreating the GmailService instance when this error occurs. Catch the HttpRequestException, dispose of the current service, and create a new one. Additionally, ensure that your system clock is accurate, as SSL validation can be sensitive to time discrepancies. Implementing explicit timeouts for the HttpClient and properly disposing of service instances has helped me mitigate this issue.

had the same issue a few months back. set ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 before you initialize the gmail service. also check for any proxy or firewall that might mess with the ssl handshake on long connections. fixed it for me.

I’ve hit this exact SSL issue with Google APIs during long-running processes. It’s usually connection pooling - your HttpClient holds onto old connections that eventually fail cert validation. Here’s what fixed it for me: wrap your Execute() call in try-catch and retry with exponential backoff when you get SSL-related HttpRequestExceptions. Also, if you’re using a custom HttpClientHandler, set a shorter connection lifetime. This forces fresh connections more often and stops stale SSL contexts from piling up.