Sending an email using the Gmail SMTP server in C#

  |   Martin Vobr

Sending an email using the Google Gmail SMTP server is not as simple as you would expect. For example, you have to authenticate to the Gmail SMTP server to send an email, but you cannot use the same password that you are using for logging into the Gmail web application. This article shows two approaches that work (as of December 2022).

To successfully authenticate, you have to:

  • Use TLS encryption.
  • Log into the SMTP server using either:
    • App Password; or
    • OAuth 2.0

The sample code below uses the Rebex SMTP library (also part of the Rebex Mail Pack).

Sending an email using an App Password

App Passwords are 16-digit passcodes that give third-party applications access to a subset of Google Account functionality.

First, generate an App Password for accessing Gmail. Then use it as a password in your code:

var smtp = new Rebex.Net.Smtp();

using (var smtp = new Smtp())
{
    // Connect to Gmail.
    smtp.Connect("smtp.gmail.com", SslMode.Implicit);

    // Use the generated App Password (without spaces).
    // Do not use your account password that you use for logging into Gmail app.
    smtp.Login("example@gmail.com", "haiqdcoiefewedxq");

    // Send the email.
    smtp.Send(from: "example@gmail.com", to: "test@example.com", subject: "test email", body: "Hi!");

    smtp.Disconnect();
}

Sending an email using OAuth - interactive applications

With OAuth 2.0, you can delegate authentication and authorization to Google. No password will be stored in your app. This setup is more complex than for App Passwords, but the result is more secure and suitable for apps operated by signed-in users.

The following code shows how to use this all together:

// Local ID used to identify the user locally
// (does not have to correspond to Google's user name).
string localId = "user123";

// Get Google's OAuth 2.0 access token.
string accessToken = GetAccessToken(localId);

// Get email associated with the token.
string email = GetEmail(accessToken);

using (var smtp = new Smtp())
{
    // Connect and log into Gmail using OAuth 2.0.
    smtp.Connect("smtp.gmail.com", SslMode.Implicit);
    smtp.Login(email, accessToken, SmtpAuthentication.OAuth20);

    // Send the email.
    smtp.Send(from: "example@gmail.com", to: "test@example.com", subject: "test email", body: "Hi!");

    smtp.Disconnect();
}

See also