2026-07-15

Send email using System.Net.Mail through gmail

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

Send email using System.Net.Mail through gmail

Sending Email via Gmail SMTP: Troubleshooting Stuck Sends in .NET

As a senior developer, I’ve seen countless developers run into issues when trying to interface with external services like Gmail for email delivery. The process of sending mail through an SMTP server, especially one as strictly secured as Google’s, often seems straightforward but quickly becomes a debugging nightmare. The issue you are facing—the code getting "stuck"—is almost always related to authentication, security protocols (SSL/TLS), or account restrictions rather than a flaw in the core System.Net.Mail syntax itself.

This post will diagnose why your email sending might be failing and provide a robust solution, along with best practices for modern application development.

Diagnosing the SMTP Failure

When an SMTP operation hangs or fails silently, it usually points to one of three major bottlenecks:

  1. Authentication Failure: This is the most common culprit with Gmail. Due to enhanced security measures (like Two-Factor Authentication), simply using your standard Google password often fails when connecting via external SMTP servers.
  2. Port and Security Mismatch: While you correctly set smtp.Host and smtp.EnableSsl = true, sometimes the specific port or TLS negotiation can cause a stall if the server rejects the connection handshake prematurely.
  3. Account Restriction: Google imposes limits on how external applications can access their mail servers, especially for non-OAuth authenticated connections.

The Solution: Authentication and Best Practices

The fundamental fix involves addressing how your application authenticates with the Gmail SMTP server. The standard username/password method is increasingly unreliable for services like Gmail.

Step 1: Using App Passwords (The Modern Approach)

If you are using a standard Google account, the most secure and reliable way to authenticate an external application is by generating an App Password. You must enable 2-Step Verification on your Google account first, and then go into your Google Security settings to generate a unique 16-character password specifically for this application. Use this generated App Password in place of your regular Google account password in the code below.

Step 2: Refined C# Implementation

Here is a refined version of your code, incorporating best practices and clearer error handling. Note that we will use the credentials directly within the setup phase.

using System.Net.Mail;
using System.Net;

public class EmailSender
{
    public void SendEmailViaGmail(string fromEmail, string toEmail, string subject, string body)
    {
        try
        {
            using (MailMessage mail = new MailMessage())
            {
                // Sender setup
                mail.From = new MailAddress(fromEmail);

                // Recipient setup
                mail.To.Add(new MailAddress(toEmail));

                // Content setup
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                mail.Body = body;

                // SMTP Client Configuration
                using (SmtpClient smtp = new SmtpClient("smtp.gmail.com"))
                {
                    smtp.Port = 465; // Use port 465 for implicit SSL
                    smtp.EnableSsl = true;
                    
                    // *** CRITICAL: Use the App Password here instead of your regular password ***
                    smtp.Credentials = new System.Net.NetworkCredential(fromEmail, "YOUR_GENERATED_APP_PASSWORD");

                    Console.WriteLine("Attempting to send email...");
                    smtp.Send(mail);
                    Console.WriteLine("Email sent successfully!");
                }
            }
        }
        catch (SmtpException ex)
        {
            // Catch specific SMTP errors for better debugging
            Console.WriteLine($"SMTP Error occurred: {ex.Message}");
            Console.WriteLine("Check if your App Password is correct and enabled.");
        }
        catch (Exception ex)
        {
            // Catch general connection or other exceptions
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}

// Example Usage
// var sender = new EmailSender();
// sender.SendEmailViaGmail("apps@xxxx.com", "yyyy@xxxx.com", "Test Subject", "This is the body of the test email.");

Architectural Context: Moving Beyond Direct SMTP

While direct use of System.Net.Mail works perfectly for simple scripts, building robust, scalable applications—especially those dealing with complex external integrations—requires a more structured approach. When architecting systems, focusing on clean separation of concerns and dependency injection is key. For instance, frameworks like Laravel emphasize creating well-defined service layers where email sending logic is abstracted away from the core business logic. This architectural discipline helps prevent these kinds of low-level integration failures from becoming systemic bugs.

Conclusion

The "stuck" issue you encountered is almost certainly an authentication hurdle. By switching to a secure method like App Passwords and implementing proper try-catch blocks around your SMTP operations, you gain much better control over error handling. Remember, when dealing with external services, always default to the most secure authentication methods provided by those services.


For further reading on building robust application architecture, explore the principles taught at https://laravelcompany.com.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.