This is Part 3 of a series on sending email.

In our last post, we looked at how to deliver email using a SmtpClient.

In this post, we will look at how to send email using Gmail.

The first issue to consider is authentication. How will we authenticate ourselves to Gmail?

To address this, we need to create an app password.

To do this, you need to visit this link ~> https://myaccount.google.com/apppasswords

AppPasswordSetup

You will be asked to provide a name for your app-specific password.

This means that you can create several, each for a different application, and revoke them as and when necessary. This is useful in situations where you retire an app or an app’s password is compromised. You can delete or regenerate a new one under those circumstances.

When you click create, you get the following screen:

GeneratedPassword

This is the password you will use, NOT your Gmail user password that you use to log in.

Once this is ready, you can proceed to write your code.

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

const string fromAddress = "conradakunga@gmail.com";
const string fromPassword = "YOUR APP PASSWORD";

// Setup the SMTP server
var smtpClient = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress, fromPassword)
};

// Create and send email
var mail = new MailMessage
{
    From = new MailAddress(fromAddress),
    Subject = "Test Email",
    Body = "This is a test email",
};

mail.To.Add("conradakunga@gmail.com");

try
{
    smtpClient.Send(mail);
    Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to send email: {ex.Message}");
}

If you run this code, you should see the following:

Email sent successfully.

Process finished with exit code 0.

You can then log in to Gmail to verify the same:

gmailInbox

The email itself:

gmailEmail

This flexibility, as with all things, is liable to be abused, so Gmail has put in place some limits to throttle usage:

GmailLimits

These are outlined in detail in this Gmail support post.

In our next post, we will look at how to send email using Office 365.

TLDR

You can use the SMTPClient to send email through Gmail.

The code is in my GitHub.

Happy hacking!