public List<MesHeader> getAllMail(UserCredential credential) { // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //get Message id and threadid List<Message> resultMes = new List<Message>(); UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me"); request.LabelIds = "INBOX"; ListMessagesResponse response = request.Execute(); resultMes.AddRange(response.Messages); request.PageToken = response.NextPageToken; //get Detail Message List<Message> resultDetail = new List<Message>(); foreach (var item in resultMes) { Message mes = new Message(); Message mesd = service.Users.Messages.Get("me", item.Id).Execute(); mes.Snippet = mesd.Snippet; mes.Id = mesd.Id; mes.LabelIds = mesd.LabelIds; mes.Payload = mesd.Payload; resultDetail.Add(mes); } List<MesHeader> mesLHeader = new List<MesHeader>(); foreach (Message itemmes in resultDetail) { MesHeader mes = new MesHeader(); mes.txt3 = itemmes.Snippet; foreach (var item in itemmes.Payload.Headers) { if (item.Name == "From") { mes.txt1 = item.Value; } else if (item.Name == "Subject") { mes.txt2 = item.Value; } else if (item.Name == "Date") { mes.txt4 = item.Value; } } //get content if (itemmes.Payload.Parts != null) { foreach (var item in itemmes.Payload.Parts) { if (item.MimeType == "text/html") { mes.content = item.Body.Data; } else if (item.MimeType == "multipart/related" || item.MimeType == "multipart/alternative") { foreach (var itemm in item.Parts) { if (itemm.MimeType == "text/html") { mes.content = itemm.Body.Data; } else if (itemm.MimeType == "multipart/related" || itemm.MimeType == "multipart/alternative") { foreach (var itemmini in itemm.Parts) { if (itemmini.MimeType == "text/html") { mes.content = itemmini.Body.Data; } } } } } } } else { mes.content = itemmes.Payload.Body.Data; } //get content when text/html null if (mes.content == null) { if (itemmes.Payload.Parts != null) { foreach (var item in itemmes.Payload.Parts) { if (item.MimeType == "text/plain") { mes.content = item.Body.Data; } else if (item.MimeType == "multipart/related" || item.MimeType == "multipart/alternative") { foreach (var itemm in item.Parts) { if (itemm.MimeType == "text/plain") { mes.content = itemm.Body.Data; } else if (itemm.MimeType == "multipart/related" || itemm.MimeType == "multipart/alternative") { foreach (var itemmini in itemm.Parts) { if (itemmini.MimeType == "text/plain") { mes.content = itemmini.Body.Data; } } } } } } } else { mes.content = itemmes.Payload.Body.Data; } } mes.idmes = itemmes.Id; mesLHeader.Add(mes); } return mesLHeader; }
public MessagesQuery(UsersResource.MessagesResource.ListRequest request, Func <MessagePart, bool> fileNameFilter) { this.request = request; FileNameFilter = fileNameFilter; }
static void Main(string[] args) { string searchFor = string.Empty; string beforeDate = string.Empty; int batchSize = 100; bool promptMsg = false; if (args.Length == 0) { Console.WriteLine("Usage: [size] [from] [before] [prompt] e.g.: 100 facebook 2014/12/31 true"); return; } try { // call example: 100 facebook 2011/12/31 if (args.Length > 0 && args[0] != null) { Int32.TryParse(args[0], out int newbatchSize); batchSize = newbatchSize > 0 ? newbatchSize : batchSize; } if (args.Length > 1 && (args[1] != null && !string.IsNullOrEmpty(args[1]))) { searchFor = args[1]; } if (args.Length > 2 && args[2] != null && !string.IsNullOrEmpty(args[2]) && DateTime.TryParse(args[2], out DateTime selectedDate)) { beforeDate = args[2]; } if (args.Length > 3 && args[3] != null) { Boolean.TryParse(args[3], out promptMsg); } 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/GMTool.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } string query = string.Empty;//$"is:unread"; if (!string.IsNullOrEmpty(searchFor)) { query += $" from:{searchFor}"; } if (!string.IsNullOrEmpty(beforeDate)) { query += $" before:{beforeDate}"; } Console.WriteLine($"The query is: {query}"); Console.WriteLine("Proceed? (Y/N)"); var readedKey = Console.ReadKey(); if (readedKey.KeyChar.ToString().ToLower() == "n") { return; } // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); IList <Message> messages; bool doWork = true; int iterator = 0; int batchnum = 0; while (doWork) { batchnum++; UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me"); request.Q = query; // "from:facebook before:2011/12/31"; #if DEBUG request.Q = "from:facebook before:2013/12/31"; #endif request.MaxResults = batchSize; messages = request.Execute().Messages; if (messages != null && messages.Count > 0 && iterator <= batchSize) { Console.WriteLine($"Found: {messages.Count} messages in batch num #{batchnum}."); if (promptMsg) { foreach (var msg in messages) { iterator++; var getRequest = service.Users.Messages.Get("me", msg.Id); var sentMsg = getRequest.Execute(); Console.WriteLine($"{iterator}/{messages.Count} - Msg: {sentMsg.Snippet}"); //UsersResource.MessagesResource.TrashRequest trashRequest = service.Users.Messages.Trash("me", msg.Id); //var result = trashRequest.Execute(); } } else { iterator += messages.Count; } Console.WriteLine($"DELETE ALL {messages.Count} MESSAGES IN CURRENT BATCH? (Y/N) -- !!! WARNING! YOU CANNOT UNDO THIS! !!!"); readedKey = Console.ReadKey(); if (readedKey.KeyChar.ToString().ToLower() == "n") { return; } var batchDeleteReq = new BatchDeleteMessagesRequest { Ids = messages.Select(e => e.Id).ToList() }; var req = service.Users.Messages.BatchDelete(batchDeleteReq, "me"); var batchDeleteResult = req.Execute(); Console.WriteLine($"Deleted {messages.Count} messages in batch num# {batchnum}"); } else { doWork = false; } } Console.WriteLine($"TOTAL Deleted {iterator} messages."); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine($"Exception occured: {ex.Message}"); } }
static void Main(string[] args) { //--------------RAZORPAY INTEGRATION------------------------- string[] RazorpayDetails = File.ReadAllLines("razorpaycredentials.txt"); RazorpayClient client = new RazorpayClient(RazorpayDetails[0], RazorpayDetails[1]); Dictionary <string, object> options = new Dictionary <string, object>(); long existingTimestamp = Convert.ToInt64(File.ReadAllText("timestamp.txt")); List <Payment> payments = client.Payment.All(options); var listPayments = payments .Where(p => p["created_at"].Value > existingTimestamp) .Where(p => p["status"].Value == "captured"); var failedPayments = payments.Where(p => p["status"].Value == "failed"); //----------------GMAIL Integration------------------------------- UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. 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. List <Message> messages = new List <Message>(); UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me"); request.LabelIds = new string[] { "SENT" }; ListMessagesResponse response = request.Execute(); var mostRecentSentMessageId = response.Messages.First().Id; var mostRecentSentMessage = service.Users.Messages.Get("me", mostRecentSentMessageId).Execute(); var toAddress = mostRecentSentMessage.Payload.Headers.Where(h => h.Name == "To").First().Value; //Remove any payments that have been emailed -- CHECK FOR MULTIPLE ORDERS FROM SAME EMAIL List <Payment> newPayments = new List <Payment>(); foreach (var payment in listPayments) { string email = payment["email"].Value; if (email == toAddress) { break; } newPayments.Add(payment); } //Going through payments to process foreach (var payment in newPayments) { long amount = payment["amount"].Value; string email = payment["email"].Value; bool captured = payment["captured"].Value; string id = payment["id"].Value; var notes = payment["notes"]; string product = (notes["product"] == null) ? string.Empty : notes["product"]; long timestamp = payment["created_at"].Value; if (timestamp != 0) { if (timestamp > existingTimestamp) { existingTimestamp = timestamp; } } if (string.IsNullOrWhiteSpace(product)) { Console.WriteLine("Transaction without product value present : email is " + email); File.WriteAllText("timestamp.txt", existingTimestamp.ToString()); return; } MimeMessage emailContent = createEmail(email, "", product); Message message = createMessageWithEmail(emailContent); var result = service.Users.Messages.Send(message, "me").Execute(); } File.WriteAllText("timestamp.txt", existingTimestamp.ToString()); }
static void Main(string[] args) { String outputDir = "H:\\Temp\\"; UserCredential credential; FaceHaarCascade cascade = new FaceHaarCascade(); HaarObjectDetector detector = new HaarObjectDetector(cascade); detector.SearchMode = ObjectDetectorSearchMode.Average; detector.ScalingFactor = 1.5F; detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;; detector.UseParallelProcessing = true; detector.Suppression = 3; 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); } // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me"); request.Q = "has:attachment"; // List labels. IList <Message> messages = request.Execute().Messages; Console.WriteLine("Messages:"); if (messages != null && messages.Count > 0) { foreach (var messageItem in messages) { //Console.WriteLine("{0}", messageItem.Id); Message message = service.Users.Messages.Get("me", messageItem.Id).Execute(); Console.WriteLine(message.Payload.MimeType.ToString()); IList <MessagePart> parts = message.Payload.Parts; foreach (MessagePart part in parts) { if (!String.IsNullOrEmpty(part.Filename)) { String attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments.Get("me", messageItem.Id, attId).Execute(); Console.WriteLine(part.Filename); // Converting from RFC 4648 base64 to base64url encoding // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history String attachData = attachPart.Data.Replace('-', '+'); attachData = attachData.Replace('_', '/'); byte[] data = Convert.FromBase64String(attachData); MemoryStream ms = new MemoryStream(data); Bitmap img = new Bitmap(Image.FromStream(ms)); Rectangle[] rects = detector.ProcessFrame(img); if (rects.Count() > 0) { Console.WriteLine("Face detected!!!!"); File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data); } } } } } else { Console.WriteLine("No messages found."); } Console.Read(); }
/// <summary> /// Asynchronous method used to synchronize the user inbox /// </summary> /// <param name="manual">Indicates if the synchronization come's from the timer tick or has been manually triggered</param> /// <param name="token">Indicates if the Gmail token need to be refreshed</param> public async void Sync(bool manual = true, bool token = false) { // prevents the application from syncing the inbox when updating if (UI.UpdateService.Updating) { return; } // updates the synchronization time Time = DateTime.Now; // resets reconnection count and prevents the application from displaying continuous warning icon when a timertick synchronization occurs after a reconnection attempt if (ReconnectionAttempts != 0) { manual = true; ReconnectionAttempts = 0; } // disables the timeout when the user do a manual synchronization if (manual && UI.NotificationService.Paused) { UI.NotificationService.Resume(); return; } // if internet is down, attempts to reconnect the user mailbox if (!UI.ComputerService.IsInternetAvailable()) { UI.timerReconnect.Enabled = true; UI.timer.Enabled = false; return; } // refreshes the token if needed if (token) { await UI.GmailService.RefreshToken(); } // activates the necessary menu items UI.menuItemSynchronize.Enabled = true; UI.menuItemTimout.Enabled = true; UI.menuItemSettings.Enabled = true; // displays the sync icon, but only on manual synchronization if (manual) { UI.notifyIcon.Icon = Resources.sync; UI.notifyIcon.Text = Translation.sync; } // do a small ping on the update service UI.UpdateService.Ping(); try { // initializes the gmail service base client api if (Api == null) { Api = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = UI.GmailService.Credential, ApplicationName = Settings.Default.APPLICATION_NAME }); // retrieves the gmail address UI.labelEmailAddress.Text = EmailAddress = Api.Users.GetProfile("me").Execute().EmailAddress; } // manages the spam notification if (Settings.Default.SpamNotification) { // exits if a spam is already detected if (!manual && UI.NotificationService.Tag == "#spam") { return; } // gets the "spam" label Label spam = await Api.Users.Labels.Get("me", "SPAM").ExecuteAsync(); // manages unread spams if (spam.ThreadsUnread > 0) { // plays a sound on unread spams if (Settings.Default.AudioNotification) { SystemSounds.Exclamation.Play(); } // displays a balloon tip in the systray with the total of unread threads UI.NotificationService.Tip(spam.ThreadsUnread.ToString() + " " + (spam.ThreadsUnread > 1 ? Translation.unreadSpams : Translation.unreadSpam), Translation.newUnreadSpam, Notification.Type.Error); // sets the notification icon and text UI.notifyIcon.Icon = Resources.spam; UI.notifyIcon.Text = spam.ThreadsUnread.ToString() + " " + (spam.ThreadsUnread > 1 ? Translation.unreadSpams : Translation.unreadSpam); // updates the tag UI.NotificationService.Tag = "#spam"; return; } } // gets the "inbox" label Box = await Api.Users.Labels.Get("me", "INBOX").ExecuteAsync(); // updates the statistics UpdateStatistics(); // exits the sync if the number of unread threads is the same as before if (!manual && (Box.ThreadsUnread == UnreadThreads)) { return; } // manages unread threads if (Box.ThreadsUnread > 0) { // sets the notification icon UI.notifyIcon.Icon = Box.ThreadsUnread <= Settings.Default.UNSTACK_BOUNDARY ? Resources.mails : Resources.stack; // manages message notification if (Settings.Default.MessageNotification) { // plays a sound on unread threads if (Settings.Default.AudioNotification) { SystemSounds.Asterisk.Play(); } // gets the message details UsersResource.MessagesResource.ListRequest messages = Api.Users.Messages.List("me"); messages.LabelIds = "UNREAD"; messages.MaxResults = 1; Google.Apis.Gmail.v1.Data.Message message = await Api.Users.Messages.Get("me", await messages.ExecuteAsync().ContinueWith(m => { return(m.Result.Messages.First().Id); })).ExecuteAsync(); // displays a balloon tip in the systray with the total of unread threads and message details, depending on the user privacy setting if (Box.ThreadsUnread == 1 && Settings.Default.PrivacyNotification != (int)Notification.Privacy.All) { string subject = ""; string from = ""; foreach (MessagePartHeader header in message.Payload.Headers) { if (header.Name == "Subject") { subject = header.Value != "" ? header.Value : Translation.newUnreadMessage; } else if (header.Name == "From") { Match match = Regex.Match(header.Value, ".* <"); if (match.Length != 0) { from = match.Captures[0].Value.Replace(" <", "").Replace("\"", ""); } else { match = Regex.Match(header.Value, "<?.*>?"); from = match.Length != 0 ? match.Value.ToLower().Replace("<", "").Replace(">", "") : header.Value.Replace(match.Value, Box.ThreadsUnread.ToString() + " " + Translation.unreadMessage); } } } if (Settings.Default.PrivacyNotification == (int)Notification.Privacy.None) { subject = message.Snippet != "" ? WebUtility.HtmlDecode(message.Snippet) : Translation.newUnreadMessage; } // detects if the message contains attachments if (message.Payload.Parts != null && message.Payload.MimeType == "multipart/mixed") { int attachments = message.Payload.Parts.Where(part => !String.IsNullOrEmpty(part.Filename)).Count(); if (attachments > 0) { from = (from.Length > 48 ? from.Substring(0, 48) : from) + " – " + attachments.ToString() + " " + (attachments > 1 ? Translation.attachments : Translation.attachment); } } UI.NotificationService.Tip(from, subject); } else { UI.NotificationService.Tip(Box.ThreadsUnread.ToString() + " " + (Box.ThreadsUnread > 1 ? Translation.unreadMessages : Translation.unreadMessage), Translation.newUnreadMessage); } // updates the notification tag to allow the user to directly display the specified view (inbox/message/spam) in a browser UI.NotificationService.Tag = "#inbox" + (Box.ThreadsUnread == 1 ? "/" + message.Id : ""); } // displays the notification text UI.notifyIcon.Text = Box.ThreadsUnread.ToString() + " " + (Box.ThreadsUnread > 1 ? Translation.unreadMessages : Translation.unreadMessage); // enables the mark as read menu item UI.menuItemMarkAsRead.Text = Translation.markAsRead + " (" + Box.ThreadsUnread + ")"; UI.menuItemMarkAsRead.Enabled = true; } else { // restores the default systray icon and text UI.notifyIcon.Icon = Resources.normal; UI.notifyIcon.Text = Translation.noMessage; // disables the mark as read menu item UI.menuItemMarkAsRead.Text = Translation.markAsRead; UI.menuItemMarkAsRead.Enabled = false; } // saves the number of unread threads UnreadThreads = Box.ThreadsUnread; } catch (Exception exception) { // displays a balloon tip in the systray with the detailed error message UI.notifyIcon.Icon = Resources.warning; UI.notifyIcon.Text = Translation.syncError; UI.NotificationService.Tip(Translation.error, Translation.syncErrorOccured + exception.Message, Notification.Type.Warning, 1500); } finally { UI.notifyIcon.Text = UI.notifyIcon.Text.Split('\n')[0] + "\n" + Translation.syncTime.Replace("{time}", Time.ToLongTimeString()); } }
/// <summary> /// Asynchronous method used to mark as read the user inbox /// </summary> public async void MarkAsRead() { try { // updates the synchronization time Time = DateTime.Now; // displays the sync icon UI.notifyIcon.Icon = Resources.sync; UI.notifyIcon.Text = Translation.sync; // gets all unread messages UsersResource.MessagesResource.ListRequest messages = Api.Users.Messages.List("me"); messages.LabelIds = "UNREAD"; ListMessagesResponse list = await messages.ExecuteAsync(); IList <Message> unread = list.Messages; // loops through all unread threads and removes the "unread" label for each one if (unread != null && unread.Count > 0) { // batch all mail ids to modify IEnumerable <string> batch = unread.Select( thread => thread.Id ); // creates the batch request BatchModifyMessagesRequest request = new BatchModifyMessagesRequest() { Ids = batch.ToList(), RemoveLabelIds = new List <string>() { "UNREAD" } }; // executes the batch request to mark all mails as read await Api.Users.Messages.BatchModify(request, "me").ExecuteAsync(); // gets the "inbox" label Box = await Api.Users.Labels.Get("me", "INBOX").ExecuteAsync(); // updates the statistics UpdateStatistics(); } // restores the default systray icon and text UI.notifyIcon.Icon = Resources.normal; UI.notifyIcon.Text = Translation.noMessage; // cleans the tag UI.NotificationService.Tag = null; // resets the number of unread threads UnreadThreads = 0; // disables the mark as read menu item UI.menuItemMarkAsRead.Text = Translation.markAsRead; UI.menuItemMarkAsRead.Enabled = false; } catch (Exception exception) { // enabled the mark as read menu item UI.menuItemMarkAsRead.Text = Translation.markAsRead + " (" + Box.ThreadsUnread + ")"; UI.menuItemMarkAsRead.Enabled = true; // displays a balloon tip in the systray with the detailed error message UI.notifyIcon.Icon = Resources.warning; UI.notifyIcon.Text = Translation.markAsReadError; UI.NotificationService.Tip(Translation.error, Translation.markAsReadErrorOccured + exception.Message, Notification.Type.Warning, 1500); } finally { UI.notifyIcon.Text = UI.notifyIcon.Text.Split('\n')[0] + "\n" + Translation.syncTime.Replace("{time}", Time.ToLongTimeString()); } }
public ActionResult LettersList(GmailService service, String userId = "*****@*****.**" /*, String query*/) { LettersListViewModel LettersListViewModel = new LettersListViewModel(); LettersListViewModel.Mails = new List <Mail>(); List <Message> result = new List <Message>(); UserCredential credential; string[] Scopes = { GmailService.Scope.GmailReadonly }; 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); } // Create Gmail API service. service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential // ApplicationName = ApplicationName, }); UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId); //request.Q = query; do { try { ListMessagesResponse response = request.Execute(); LettersListViewModel.Mails.AddRange(response.Messages); //result.AddRange(response.Messages); request.PageToken = response.NextPageToken; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } } while (!String.IsNullOrEmpty(request.PageToken)); return(View(LettersListViewModel)); //Mail mail; //WebClient objclient = new WebClient(); //string response = null; //XmlDocument xdoc = new XmlDocument(); //LettersListViewModel LettersListViewModel = new LettersListViewModel(); //LettersListViewModel.Mails = new List<Mail>(); //objclient.Credentials = new NetworkCredential(IndexViewModel.Login, IndexViewModel.Password); //response = Encoding.UTF8.GetString(objclient.DownloadData("https://mail.google.com/mail/feed/atom")); //response = response.Replace("<feed version=\"0.3\" xmlns=\"http://purl.org/atom/ns#\">", "<feed>"); //xdoc.LoadXml(response); //foreach (XmlNode node1 in xdoc.SelectNodes("feed/entry")) //{ // mail = new Mail(); // mail.From = node1.SelectSingleNode("author/email").InnerText; // mail.Title = node1.SelectSingleNode("title").InnerText; // mail.Summary = node1.SelectSingleNode("summary").InnerText; // LettersListViewModel.Mails.Add(mail); //} //return View(LettersListViewModel); }
public static void Run() { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. 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. GmailService service = new GmailService( new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. // UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me"); UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me"); request.MaxResults = 10; // List labels. // IList<Label> labels = request.Execute().Labels; // Console.WriteLine("Labels:"); // if (labels != null && labels.Count > 0) // { // foreach (var labelItem in labels) // { // Console.WriteLine("{0}", labelItem.Name); // } // } // else // { // Console.WriteLine("No labels found."); // } Console.WriteLine(request.Execute().Messages.Count); IList <Message> msgs = request.Execute().Messages; if (msgs?.Count > 0) { string lastMsg = string.Empty; int cnt = 1; foreach (var item in msgs) { Console.WriteLine( $"{cnt++}\r\n{item.Id}\r\n"); lastMsg = item.Id.ToString(); } var TEST = GetMessage(service, "me", lastMsg); Console.WriteLine(TEST.Payload.Body); Console.WriteLine(TEST.Payload.Body.Data); Console.WriteLine(TEST.Payload.Filename); Console.WriteLine(TEST.Payload.Parts.Count); Console.WriteLine(TEST.Payload.Parts[0].Filename); Console.WriteLine(TEST.Payload.Parts[0].Body.Data); Console.WriteLine(TEST.Payload.Parts[1].Body.Data); // Base64decode : string base64Encoded = "0K3RhS4uLg0KD"; // TEST.Payload.Parts[0].Body.Data.ToString(); //var TET = Base64UrlDecode(base64encoded); //string base64Decoded; byte[] data = Convert.FromBase64String(base64Encoded); //base64Decoded = System.Text.Encoding.ASCII.GetString(data); // var message_data = TEST.Payload.Parts[0].Body.Data; // var json_data = JSON.parse(message_data.to_json) // var decoded_message = Base64.urlsafe_decode64(json_data["body"]["data"]) } else { Console.WriteLine("No msgs found."); } }
internal static void ReadMails(GmailService service, string userId) { try { string defaultSubjectValue = "Trello"; UsersResource.MessagesResource.ListRequest inboxlistRequest = service.Users.Messages.List(userId); inboxlistRequest.LabelIds = "INBOX"; inboxlistRequest.Q = "is:unread"; inboxlistRequest.IncludeSpamTrash = false; ListMessagesResponse emailListResponse = inboxlistRequest.Execute(); if (emailListResponse != null && emailListResponse.Messages != null) { List <Message> newMessageList = new List <Message>(); if (MessagesList == null) { MessagesList = new List <Message>(); } foreach (Message email in emailListResponse.Messages) { UsersResource.MessagesResource.GetRequest emailInfoRequest = service.Users.Messages.Get(userId, email.Id); Message emailInfoResponse = emailInfoRequest.Execute(); if (emailInfoResponse != null) { string subjectValue = emailInfoResponse.Payload.Headers.Where(header => header.Name == "Subject") .Select(subj => subj.Value).ToArray().First(); if (subjectValue.Contains(defaultSubjectValue)) { newMessageList.Add(emailInfoResponse); if (MessagesList.Find(x => x.Id == emailInfoResponse.Id) == null) { string cardBody = emailInfoResponse.Snippet; TrelloInformation information = TrelloUtilities.CreateDefaultTrelloInformation(subjectValue, cardBody); string cardId = TrelloUtilities.MakeAndPostTrelloCard(information); if (cardId != null) { GmailMessageObject gmailMessage = CreateGmailObject(emailInfoResponse, cardId); if (gmailMessage != null) { GmailXTrelloMessagesList.Add(gmailMessage); } Console.WriteLine("Card criado com sucesso! "); } else { Console.WriteLine("Não foi possível criar o Card."); } } } } } List <Message> returnedList = MessageListVerifier(newMessageList); if (returnedList != null) { MoveEmailToReadCard(returnedList); } } } catch (Exception error) { Tools.LogWriter.WriteLog(error.Message); } }