Skip to content

Instantly share code, notes, and snippets.

@AnshulKuthiala
Created November 10, 2018 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AnshulKuthiala/bf085747185b92a7ed6fb7cd332eecbf to your computer and use it in GitHub Desktop.
Save AnshulKuthiala/bf085747185b92a7ed6fb7cd332eecbf to your computer and use it in GitHub Desktop.
[Gmail API] Access Gmail Api from C#
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Hosting;
namespace web_api.Common
{
public class GmailMessage
{
public string Subject { get; set; }
public IEnumerable<string> TO { get; set; }
public IEnumerable<string> CC { get; set; }
public IEnumerable<string> Bcc { get; set; }
public string HtmlBody { get; set; }
public GmailMessage(string subject, IEnumerable<string> to, string htmlBody)
{
Subject = subject;
TO = to;
CC = null;
Bcc = null;
HtmlBody = htmlBody;
}
public GmailMessage(string subject, IEnumerable<string> to, IEnumerable<string> cc, string htmlBody)
{
Subject = subject;
TO = to;
CC = cc;
Bcc = null;
HtmlBody = htmlBody;
}
public GmailMessage(string subject, IEnumerable<string> to, IEnumerable<string> cc, IEnumerable<string> bcc, string htmlBody)
{
Subject = subject;
TO = to;
CC = cc;
Bcc = bcc;
HtmlBody = htmlBody;
}
}
public class GmailSendService
{
public string SenderName { get; set; }
private GmailService GmailService { get; set; }
private Message InternalMessage { get; set; }
//User Inputs
static string[] Scopes = { GmailService.Scope.MailGoogleCom };
static string ApplicationName = "Email Application";
static string SenderEmail = "kuthiala.anshul@gmail.com";
public GmailSendService(string senderName)
{
SenderName = senderName;
UserCredential credential;
string gmailPath = HostingEnvironment.MapPath(@"~/App_Data/Gmail");
using (var stream = new FileStream($"{gmailPath}/GmailKey.json", FileMode.Open, FileAccess.Read))
{
string credPath = $"{gmailPath}/.credentials/gmail-dotnet-credentials.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Gmail API service.
GmailService = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
public async Task SendMailAsync(GmailMessage message)
{
try
{
GetSendMessage(message);
await GmailService.Users.Messages.Send(InternalMessage, "me").ExecuteAsync();
}
catch (Exception)
{
throw;
}
}
public void SendMail(GmailMessage message)
{
try
{
GetSendMessage(message);
GmailService.Users.Messages.Send(InternalMessage, "me").Execute();
}
catch (Exception)
{
throw;
}
}
private void GetSendMessage(GmailMessage gmailMessage)
{
string plainText = $"From:{SenderName}<{SenderEmail}>\r\n" +
$"To:{GenerateReceipents(gmailMessage.TO)}\r\n" +
$"CC:{GenerateReceipents(gmailMessage.CC)}\r\n" +
$"Bcc:{GenerateReceipents(gmailMessage.Bcc)}\r\n" +
$"Subject:{gmailMessage.Subject}\r\n" +
"Content-Type: text/html; charset=us-ascii\r\n\r\n" +
$"{gmailMessage.HtmlBody}";
Message message = new Message();
message.Raw = Encode(plainText.ToString());
InternalMessage = message;
}
private string GenerateReceipents(IEnumerable<string> receipents)
{
return receipents == null ? string.Empty : string.Join(",", receipents);
}
private string Encode(string text)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment