How to configure SMTP client for Gmail email delivery in C#

I’m trying to set up email functionality in my C# application using Gmail’s SMTP server but running into issues. The application seems to hang when attempting to send messages and I’m not sure what’s causing the problem.

Here’s my current implementation:

EmailMessage message = new EmailMessage();
message.From = new System.Net.Mail.MailAddress("[email protected]");

SmtpClient client = new SmtpClient();
client.Port = 465;
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;

message.To.Add(new MailAddress("[email protected]"));
message.IsBodyHtml = true;
string content = "Hello World";
message.Body = content;
client.Send(message);

I’m using a custom domain hosted on Google Workspace. Has anyone encountered similar issues with Gmail SMTP configuration? What could be causing the hanging behavior?

Your hanging issue is likely due to authentication problems mixed with port settings. Since you have UseDefaultCredentials set to true, the SMTP client attempts to authenticate using your Windows credentials rather than your Gmail account, which leads to failure and timeouts. To fix this, set UseDefaultCredentials to false and provide the appropriate credentials using: client.Credentials = new NetworkCredential(“[email protected]”, “your-app-password”). Additionally, consider switching to port 587 with STARTTLS instead of 465, as the former is generally more reliable for .NET applications. With Google Workspace, make sure to enable less secure app access or, preferably, use an App Password instead of your regular password. This authentication mismatch is likely the reason your app is hanging during the send operation.

check your firewall settings - i had the same hanging issue with gmail smtp when my firewall was blocking outbound connections on port 465. also verify that smtp auth is enabled in your google workspace admin console. it’s sometimes disabled by default and causes silent failures.

Had the same Gmail SMTP hanging issue in production last year. Your problem is using port 465 with the default SSL setup in SmtpClient. Port 465 uses implicit SSL and causes timeouts when the SSL handshake fails. Switch to port 587 - it uses explicit SSL through STARTTLS and works way better with .NET’s SmtpClient. Drop UseDefaultCredentials = true and use explicit credentials with NetworkCredential instead. If you’re on Google Workspace, generate an App Password through Google Admin console instead of your regular password. Also wrap your SmtpClient in a using statement - connection pooling issues can cause hanging on later sends.