Created
August 14, 2018 23:24
-
-
Save PaulDMendoza/fc29fd9f1c9f46a85683711a785cf917 to your computer and use it in GitHub Desktop.
SigParser C# Gmail Full Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ExampleSigParserApp | |
{ | |
class Program | |
{ | |
static string[] Scopes = { GmailService.Scope.GmailReadonly }; | |
static string ApplicationName = "Gmail API .NET Quickstart"; | |
static void Main(string[] args) | |
{ | |
var sigParserApiKeyString = "sdfsdfsdflksndfklsdf"; | |
UserCredential credential; | |
using (var stream = | |
new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) | |
{ | |
string credPath = "token.json"; | |
credential = GoogleWebAuthorizationBroker.AuthorizeAsync( | |
GoogleClientSecrets.Load(stream).Secrets, | |
Scopes, | |
"user", | |
CancellationToken.None, | |
new FileDataStore(credPath, true)).Result; | |
Console.WriteLine("Credential file saved to: " + credPath); | |
} | |
// Create Gmail API service. | |
var service = new GmailService(new BaseClientService.Initializer() | |
{ | |
HttpClientInitializer = credential, | |
ApplicationName = ApplicationName, | |
}); | |
// Define parameters of request. | |
var request = service.Users.Messages.List("me"); | |
var response = request.Execute(); | |
while (response != null) | |
{ | |
IList<Message> messages = response.Messages; | |
Console.WriteLine("Messages:"); | |
if (messages != null && messages.Count > 0) | |
{ | |
foreach (var message in messages) | |
{ | |
var messageReq = service.Users.Messages.Get("me", message.Id); | |
messageReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full; | |
var m = messageReq.Execute(); | |
var html = DecodeBase64(m.Payload.Parts.FirstOrDefault(f => f.MimeType == "text/html")?.Body?.Data); | |
var plain = DecodeBase64(m.Payload.Parts.FirstOrDefault(f => f.MimeType == "text/plain")?.Body?.Data); | |
var fromHeader = m.Payload.Headers?.FirstOrDefault(f => f.Name == "From")?.Value; | |
var senderEmailMatch = System.Text.RegularExpressions.Regex.Match(fromHeader, "<(.+)>"); | |
var senderEmail = senderEmailMatch.Groups[1].Value; | |
var senderName = fromHeader.Substring(0, senderEmailMatch.Index); | |
var client = new SigParser.Client(sigParserApiKeyString); | |
var emailResult = client.Parse(new SigParser.EmailParseRequest | |
{ | |
from_address = senderEmail, | |
from_name = senderName, | |
htmlbody = html, | |
plainbody = plain | |
}).Result; | |
Console.WriteLine("Email"); | |
foreach (var c in emailResult.contacts) | |
{ | |
Console.WriteLine( | |
$@" | |
----------------------- | |
{c.firstName} {c.lastName} | |
Mobile: {c.mobilePhone} | |
Office: {c.officePhone} | |
Address: {c.address} | |
Email: {c.emailAddress} | |
LinkedIn: {c.linkedInUrl} | |
Twitter: {c.twitterUrl} | |
"); | |
} | |
// Makes it easy to see what's going on. Remove for real. | |
Console.ReadLine(); | |
} | |
} | |
if (!String.IsNullOrWhiteSpace(response.NextPageToken)) | |
{ | |
request.PageToken = response.NextPageToken; | |
response = request.Execute(); | |
} | |
else | |
{ | |
response = null; | |
} | |
} | |
Console.WriteLine("Done"); | |
Console.Read(); | |
} | |
///<summary> | |
/// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8. | |
///</summary> | |
///<param name="str">Base64 code</param> | |
///<returns>The decoded string.</returns> | |
public static string DecodeBase64(string str) | |
{ | |
if (str == null) | |
return str; | |
int padChars = (str.Length % 4) == 0 ? 0 : (4 - (str.Length % 4)); | |
StringBuilder result = new StringBuilder(str, str.Length + padChars); | |
result.Append(String.Empty.PadRight(padChars, '=')); | |
result.Replace('-', '+'); | |
result.Replace('_', '/'); | |
var data = Convert.FromBase64String(result.ToString()); | |
string decodedString = Encoding.UTF8.GetString(data); | |
return decodedString; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment