Windows Forms: Send an email using gmail API in C#

This post shows you How to send an email using Gmail API in C# Windows Forms Application.

To send an email via Gmail API, you need to enable your Gmail API by accessing https://console.developers.google.com/ website

Set up your Google Cloud Project

Go to the Google Cloud Console (https://console.cloud.google.com/), then create a new project or select an existing one. Next, Enable the Gmail API for your project.

Finally, Create credentials for your project to access the API, then you will receive a client ID and client secret.

Install Google API Client Library

Creating a new windows forms project, then install the Google API Client Library using NuGet Package Manager. Search for Google.Apis.Gmail and install the latest version.

Drag the TextBox, Label and Button from your visual studio toolbox to your winform, then design a simple UI that allows you to send an email in c# as shown below.

send email using gmail api c#

To play the demo, you should download the credentials.json file from the google console developer, then enable the Gmail API allow you to send an email using gmail api in c#.

You need to authenticate your application with the Gmail API using OAuth 2.0. This involves obtaining an access token.

You can follow the OAuth 2.0 flow for web applications or installed applications depending on your application type.

Once authenticated, you will receive an access token which you can use to make requests to the Gmail API.

Create a Base64UrlEncode method to encode your url as the following code.

string[] Scopes = { GmailService.Scope.GmailSend };
string ApplicationName = "SendMail";

string Base64UrlEncode(string input)
{
    var data = Encoding.UTF8.GetBytes(input);
    return Convert.ToBase64String(data).Replace("+", "-").Replace("/", "_").Replace("=", "");
}

Next, Double click the Send button to add a click event handler to handle email sending using the Gmail API

//c# api gmail email
private void btnSend_Click(object sender, EventArgs e)
{
    UserCredential credential;
    //read your credentials file
    using (FileStream stream = new FileStream(Application.StartupPath + @"/credentials.json", FileMode.Open, FileAccess.Read))
    {
        string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        path = Path.Combine(path, ".credentials/gmail-dotnet-quickstart.json");
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(path, true)).Result;
    }
    string message = $"To: {txtTo.Text}\r\nSubject: {txtSubject.Text}\r\nContent-Type: text/html;charset=utf-8\r\n\r\n<h1>{txtMessage.Text}</h1>";
    //call your gmail service
    var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName });
    var msg = new Google.Apis.Gmail.v1.Data.Message();
    msg.Raw = Base64UrlEncode(message.ToString());
    service.Users.Messages.Send(msg, "me").Execute();
    MessageBox.Show("Your email has been successfully sent !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

And don't forget to import the namespaces below to your form.

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Services;
using Google.Apis.Util.Store;

With the Gmail API, you can perform various operations such as listing messages, retrieving message details, sending emails, etc.

You can use the Users.Messages resource to interact with Gmail messages.

To send an email using gmail api in c# you should copy the credentials.json file that you downloaded into your project, the set the Copy to Output Directory properties to copy always.