To Read Gmail Inbox From Google API

Introduction

To Read Gmail Inbox from Google Api (from, date , subject , body of the email)

Building the Sample

To Read Gmail Inbox from Google Api (from, date , subject , body of the email)

Description

In this section we are going to see about reading Gmail inbox from Google api. Please use your email id for configuration and do not share secret key to anyone.

Please refer below link to get your client secret key from Google

https://developers.google.com/gmail/api/quickstart/dotnet

You can able to get from, date, subject and body of the email.

To connect Google Api with client secret key

  1. using(var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {  
  2.     string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);  
  3.     credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");  
  4.     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;  
  5.     Console.WriteLine("Credential file saved to: " + credPath);  
  6. }  
  7. foreach(MessagePart p in emailInfoResponse.Payload.Parts) {  
  8.     if (p.MimeType == "text/html") {  
  9.         byte[] data = FromBase64ForUrlString(p.Body.Data);  
  10.         string decodedString = Encoding.UTF8.GetString(data);  
  11.     }  
  12. }  

C#

  1. using Google.Apis.Auth.OAuth2;  
  2. using Google.Apis.Gmail.v1;  
  3. using Google.Apis.Gmail.v1.Data;  
  4. using Google.Apis.Services;  
  5. using Google.Apis.Util.Store;  
  6. using System;  
  7. using System.Collections.Generic;  
  8. using System.IO;  
  9. using System.Linq;  
  10. using System.Text;  
  11. using System.Threading;  
  12. using System.Threading.Tasks;  
  13. namespace GmailInboxApi {  
  14.     class Program {  
  15.         // If modifying these scopes, delete your previously saved credentials   
  16.         // at ~/.credentials/gmail-dotnet-quickstart.json   
  17.         static string[] Scopes = {  
  18.             GmailService.Scope.GmailReadonly  
  19.         };  
  20.         static string ApplicationName = "Gmail API .NET Quickstart";  
  21.         static void Main(string[] args) {  
  22.             UserCredential credential;  
  23.             using(var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {  
  24.                 string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);  
  25.                 credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");  
  26.                 credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;  
  27.                 Console.WriteLine("Credential file saved to: " + credPath);  
  28.             }  
  29.             // Create Gmail API service.   
  30.             var service = new GmailService(new BaseClientService.Initializer() {  
  31.                 HttpClientInitializer = credential,  
  32.                     ApplicationName = ApplicationName,  
  33.             });  
  34.             var inboxlistRequest = service.Users.Messages.List("your email id");  
  35.             inboxlistRequest.LabelIds = "INBOX";  
  36.             inboxlistRequest.IncludeSpamTrash = false;  
  37.             //get our emails   
  38.             var emailListResponse = inboxlistRequest.Execute();  
  39.             if (emailListResponse != null && emailListResponse.Messages != null) {  
  40.                 //loop through each email and get what fields you want...   
  41.                 foreach(var email in emailListResponse.Messages) {  
  42.                     var emailInfoRequest = service.Users.Messages.Get("your email id", email.Id);  
  43.                     var emailInfoResponse = emailInfoRequest.Execute();  
  44.                     if (emailInfoResponse != null) {  
  45.                         String from = "";  
  46.                         String date = "";  
  47.                         String subject = "";  
  48.                         //loop through the headers to get from,date,subject, body  
  49.                         foreach(var mParts in emailInfoResponse.Payload.Headers) {  
  50.                             if (mParts.Name == "Date") {  
  51.                                 date = mParts.Value;  
  52.                             } else if (mParts.Name == "From") {  
  53.                                 from = mParts.Value;  
  54.                             } else if (mParts.Name == "Subject") {  
  55.                                 subject = mParts.Value;  
  56.                             }  
  57.                             if (date != "" && from != "") {  
  58.                                 foreach(MessagePart p in emailInfoResponse.Payload.Parts) {  
  59.                                     if (p.MimeType == "text/html") {  
  60.                                         byte[] data = FromBase64ForUrlString(p.Body.Data);  
  61.                                         string decodedString = Encoding.UTF8.GetString(data);  
  62.                                     }  
  63.                                 }  
  64.                             }  
  65.                         }  
  66.                     }  
  67.                 }  
  68.             }  
  69.             Console.ReadLine();  
  70.         }  
  71.         public static byte[] FromBase64ForUrlString(string base64ForUrlInput) {  
  72.             int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));  
  73.             StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);  
  74.             result.Append(String.Empty.PadRight(padChars, '='));  
  75.             result.Replace('-''+');  
  76.             result.Replace('_''/');  
  77.             return Convert.FromBase64String(result.ToString());  
  78.         }  
  79.     }  
  80. }  

More Information

Please visit below link

https://developers.google.com/gmail/api/quickstart/dotnet