C#
Gmail SMTP
email sending
programming
coding tutorial

Sending email through Gmail SMTP server with C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

You can send email from C# through Gmail's SMTP service, but the important part is not just setting smtp.gmail.com and port 587. You also need the right authentication model, secure credential handling, and realistic expectations about Gmail's policy restrictions. In current practice, the simplest workable setup for a small app is usually SMTP with an app password on an account that has 2-step verification enabled.

Know What Gmail Will and Will Not Accept

Gmail supports SMTP submission, but it does not want arbitrary applications logging in with your ordinary account password through weak authentication settings. Older tutorials often mention “less secure apps,” but that is outdated and not the right direction for new code.

For a straightforward C# SMTP client, the typical setup is:

  • use a Gmail or Google Workspace account
  • enable 2-step verification
  • create an app password for SMTP
  • connect to smtp.gmail.com on port 587
  • enable TLS

That gives your application a dedicated credential rather than reusing your main account password.

Basic C# Example with SmtpClient

For small internal tools or legacy code, SmtpClient still illustrates the SMTP flow clearly.

csharp
1using System;
2using System.Net;
3using System.Net.Mail;
4
5class Program
6{
7    static void Main()
8    {
9        var from = new MailAddress("[email protected]", "Demo App");
10        var to = new MailAddress("[email protected]");
11        const string appPassword = "your-app-password";
12
13        using var message = new MailMessage(from, to)
14        {
15            Subject = "SMTP test from C#",
16            Body = "This message was sent through Gmail SMTP.",
17            IsBodyHtml = false
18        };
19
20        using var client = new SmtpClient("smtp.gmail.com", 587)
21        {
22            Credentials = new NetworkCredential(from.Address, appPassword),
23            EnableSsl = true
24        };
25
26        client.Send(message);
27        Console.WriteLine("Mail sent.");
28    }
29}

This example is enough to prove connectivity and authentication. For production use, you should move the credential to configuration or a secret store instead of hard-coding it.

Prefer Secret Storage Over Source-Code Credentials

Even for a small app, do not leave SMTP credentials inside source files. Load them from environment variables, user secrets, or a secure secret manager.

A simple environment-variable approach looks like this:

csharp
1using System;
2using System.Net;
3using System.Net.Mail;
4
5string username = Environment.GetEnvironmentVariable("GMAIL_SMTP_USER")!;
6string password = Environment.GetEnvironmentVariable("GMAIL_SMTP_APP_PASSWORD")!;
7
8using var message = new MailMessage(username, "[email protected]")
9{
10    Subject = "Configured SMTP mail",
11    Body = "Loaded credentials from environment variables."
12};
13
14using var client = new SmtpClient("smtp.gmail.com", 587)
15{
16    Credentials = new NetworkCredential(username, password),
17    EnableSsl = true
18};
19
20client.Send(message);

That still uses SMTP, but it removes the most obvious credential-management mistake.

Understand the Port and TLS Settings

Port 587 is the normal submission port with TLS negotiation. In .NET, that means setting EnableSsl = true so the connection is secured.

If you omit TLS, Gmail will reject the connection or the authentication flow will fail. The exact exception text varies, but the root cause is usually policy or authentication setup, not a C# syntax problem.

When SmtpClient Is Not Enough

SmtpClient is still available, but it is old and limited. For more robust mail handling, attachments, MIME control, and modern authentication workflows, many teams prefer MailKit.

A MailKit example is still straightforward:

csharp
1using MailKit.Net.Smtp;
2using MimeKit;
3
4var message = new MimeMessage();
5message.From.Add(MailboxAddress.Parse("[email protected]"));
6message.To.Add(MailboxAddress.Parse("[email protected]"));
7message.Subject = "MailKit example";
8message.Body = new TextPart("plain") { Text = "Sent with MailKit." };
9
10using var client = new SmtpClient();
11client.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
12client.Authenticate("[email protected]", "your-app-password");
13client.Send(message);
14client.Disconnect(true);

This is often the better long-term choice if the application's email needs are more than minimal.

Diagnose Failures by Category

If sending fails, separate the problem into one of these buckets:

  • authentication failed
  • TLS or port mismatch
  • blocked sign-in policy
  • invalid sender or recipient address
  • network connectivity issue

That classification is more useful than staring only at the final exception message.

Common Pitfalls

The most common mistake is using the regular Gmail password instead of an app password on an account configured for SMTP access.

Another mistake is hard-coding credentials in source control. Even for a demo, that habit creates avoidable risk.

Developers also forget that Gmail policy changes matter. A tutorial that worked years ago may describe a login flow that Google no longer permits.

Summary

  • Gmail SMTP from C# works, but the setup must match Google's current authentication rules.
  • The usual SMTP endpoint is smtp.gmail.com on port 587 with TLS enabled.
  • Use an app password instead of your normal Gmail password.
  • Keep credentials in configuration or a secret store, not in source code.
  • For more advanced scenarios, consider MailKit instead of relying only on legacy SmtpClient.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.