C# SMTP Client Gmail Connection Error - Unable to Send Email

I’m having trouble sending emails through Gmail using C# and keep running into connection issues. Every time I try to connect, I get an error saying the connection was refused by the server.

Here’s what I’m trying to do:

public static void SendEmailMethod()
{
    var smtpClient = new SmtpClient("smtp.gmail.com", 587)
    {
        Credentials = new NetworkCredential("[email protected]", "mypassword"),
        EnableSsl = true
    };
    smtpClient.Send("[email protected]", "[email protected]", "Test Subject", "Test Message");
}

I also tried a different approach with MailMessage:

public static void AlternativeMethod()
{
    var senderEmail = new MailAddress("[email protected]", "Sender Name");
    var recipientEmail = new MailAddress("[email protected]", "Recipient Name");
    const string emailPassword = "mypassword";
    const string emailSubject = "Test Email";
    const string emailBody = "This is a test message";
    
    var smtpServer = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(senderEmail.Address, emailPassword)
    };
    
    using (var emailMessage = new MailMessage(senderEmail, recipientEmail)
    {
        Subject = emailSubject,
        Body = emailBody
    })
    {
        smtpServer.Send(emailMessage);
    }
}

Both methods give me the same socket exception error. Has anyone successfully sent emails through Gmail using C#? What am I missing here?

That socket exception is probably Gmail’s tighter security restrictions. Everyone’s mentioned app passwords, but there’s another issue I see a lot - your firewall or antivirus might be blocking SMTP connections on port 587. I had this exact problem six months ago and wasted hours debugging code when it was just my corporate firewall. Try turning off your firewall/antivirus temporarily to test. Also, check if your ISP blocks port 587 - some do. If they’re blocking it, switch to port 465 with SSL, though 587 is usually better. Your code looks fine otherwise.

Had this exact problem last month. Gmail blocks these connections by default now, even with correct credentials. You’ll need to set up 2-factor authentication on your Google account first, then generate an App Password for your app. Go to Google Account settings → Security → App Passwords and create one for Mail. Use that 16-character password in your code instead of your regular one. Your SMTP setup looks right - port 587 with SSL is what Gmail needs.

for sure, try using an app password instead. regular passwords dont work if 2FA is on. create one in your google account settings and it should sort out the connection problem.