This tutorial will show you how to send an email in windows forms application using Gmail API in C#. As you know, Google allows us to access services via Google API.
To play the demo, you need to visit https://console.developers.google.com to enable Gmail API, then create a new visual C# Windows Forms Application project in Visual Studio and install Google.Apis.Gmail.v1 from nuget package manager or you can download it directly from https://www.nuget.org/packages/Google.Apis.Gmail.v1/
OK, Now we are going to design a simple UI that allows us to send an email as shown below.
I'm using Label, TextBox and Button control to design my windows forms application
Add code to handle the send button as the following.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace SendGmail
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//using gmail scope
static string[] Scopes = { GmailService.Scope.GmailSend };
static string ApplicationName = "SendMail";
public static string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(inputBytes).Replace("+", "-").Replace("/", "_").Replace("=", "");
}
private void btnSend_Click(object sender, EventArgs e)
{
UserCredential credential;
//read credentials file
using (FileStream stream = new FileStream(Application.StartupPath + @"/credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
}
string plainText = $"To: {txtTo.Text}\r\n" +
$"Subject: {txtSubject.Text}\r\n" +
"Content-Type: text/html; charset=utf-8\r\n\r\n" +
$"<h1>{txtMessage.Text}</h1>";
//call gmail service
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var newMsg = new Google.Apis.Gmail.v1.Data.Message();
newMsg.Raw = Base64UrlEncode(plainText.ToString());
service.Users.Messages.Send(newMsg, "me").Execute();
MessageBox.Show("Your email has been successfully sent !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
You need to download the credentials.json file from your google console developer, then enable the Gmail API.
Next, Copy the file that you downloaded to your project and set Copy to Output Directory properties-> copy always