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
- using(var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {
- string credPath = System.Environment.GetFolderPath(System.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;
- Console.WriteLine("Credential file saved to: " + credPath);
- }
- foreach(MessagePart p in emailInfoResponse.Payload.Parts) {
- if (p.MimeType == "text/html") {
- byte[] data = FromBase64ForUrlString(p.Body.Data);
- string decodedString = Encoding.UTF8.GetString(data);
- }
- }
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.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace GmailInboxApi {
- class Program {
-
-
- static string[] Scopes = {
- GmailService.Scope.GmailReadonly
- };
- static string ApplicationName = "Gmail API .NET Quickstart";
- static void Main(string[] args) {
- UserCredential credential;
- using(var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {
- string credPath = System.Environment.GetFolderPath(System.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;
- Console.WriteLine("Credential file saved to: " + credPath);
- }
-
- var service = new GmailService(new BaseClientService.Initializer() {
- HttpClientInitializer = credential,
- ApplicationName = ApplicationName,
- });
- var inboxlistRequest = service.Users.Messages.List("your email id");
- inboxlistRequest.LabelIds = "INBOX";
- inboxlistRequest.IncludeSpamTrash = false;
-
- var emailListResponse = inboxlistRequest.Execute();
- if (emailListResponse != null && emailListResponse.Messages != null) {
-
- foreach(var email in emailListResponse.Messages) {
- var emailInfoRequest = service.Users.Messages.Get("your email id", email.Id);
- var emailInfoResponse = emailInfoRequest.Execute();
- if (emailInfoResponse != null) {
- String from = "";
- String date = "";
- String subject = "";
-
- foreach(var mParts in emailInfoResponse.Payload.Headers) {
- if (mParts.Name == "Date") {
- date = mParts.Value;
- } else if (mParts.Name == "From") {
- from = mParts.Value;
- } else if (mParts.Name == "Subject") {
- subject = mParts.Value;
- }
- if (date != "" && from != "") {
- foreach(MessagePart p in emailInfoResponse.Payload.Parts) {
- if (p.MimeType == "text/html") {
- byte[] data = FromBase64ForUrlString(p.Body.Data);
- string decodedString = Encoding.UTF8.GetString(data);
- }
- }
- }
- }
- }
- }
- }
- Console.ReadLine();
- }
- public static byte[] FromBase64ForUrlString(string base64ForUrlInput) {
- int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
- StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
- result.Append(String.Empty.PadRight(padChars, '='));
- result.Replace('-', '+');
- result.Replace('_', '/');
- return Convert.FromBase64String(result.ToString());
- }
- }
- }
More Information
Please visit below link
https://developers.google.com/gmail/api/quickstart/dotnet
Gabe TowerPosted Mar 16, 2021, 7:51 PM
How to delete emails that's the question
sag sagPosted Sep 5, 2020, 7:00 AM
Suppose 2_step verification is on for the emailid, how set email status read after reading that through code?
Menda LukusaPosted Aug 10, 2020, 4:14 PM
What about reading shared mailbox where I have full delegation right?
Ramesh VishwakarmaPosted Jun 12, 2020, 2:03 AM
Is Google API is free to read the mails through C# code , or we need to buy the licence ?
Sathiyamoorthy SPosted Apr 12, 2018, 11:23 AM
Please check and let me know if you are facing any issues thanks.
Sathiyamoorthy SPosted Apr 12, 2018, 11:23 AM
Please find below download link for complete samle http://dotnetlearningschool.com/2018/04/12/to-read-gmail-inbox-from-google-api/
Bala SPosted Apr 11, 2018, 9:51 AM
If you have screenshots of this explanation please attach it.