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

This tutorial shows you how to send an email using gmail api in C#.NET 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, then create a new windows forms project and install the Google.Apis.Gmail.v1 from the Nuget Manage Packages.

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#.

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("=", "");
}

Finally, Add code to handle the btnSend_Click event as shown below.

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;

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.