/// <summary> /// Modifies the labels applied to the thread. This applies to all messages in the thread. /// Documentation https://developers.google.com/gmail/v1/reference/threads/modify /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated gmail service.</param> /// <param name="userId">The user's email address. The special value me can be used to indicate the authenticated user.</param> /// <param name="id">The ID of the thread to modify.</param> /// <param name="body">A valid gmail v1 body.</param> /// <returns>ThreadResponse</returns> public static Thread Modify(gmailService service, string userId, string id, ModifyThreadRequest body) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (body == null) { throw new ArgumentNullException("body"); } if (userId == null) { throw new ArgumentNullException(userId); } if (id == null) { throw new ArgumentNullException(id); } // Make the request. return(service.Threads.Modify(body, userId, id).Execute()); } catch (Exception ex) { throw new Exception("Request Threads.Modify failed.", ex); } }
public async Task markMailUnreadAsync(string id) { var markAsReadRequest = new ModifyThreadRequest { RemoveLabelIds = new[] { "UNREAD" } }; await _service.Users.Threads.Modify(markAsReadRequest, "me", id).ExecuteAsync(); }
bool markMailUnread(string mailId) { var markAsReadRequest = new ModifyThreadRequest { RemoveLabelIds = new[] { "UNREAD" } }; _service.Users.Threads.Modify(markAsReadRequest, "me", mailId).Execute(); return(true); }
//Modifica la etiqueta de correo como LEÍDO: public static Google.Apis.Gmail.v1.Data.Thread ModifyThread(GmailService oService, string threadId, IList <String> labelsToAdd, IList <String> labelsToRemove) { ModifyThreadRequest modify = new ModifyThreadRequest(); modify.AddLabelIds = labelsToAdd; modify.RemoveLabelIds = labelsToRemove; try { return(oService.Users.Threads.Modify(modify, _userId, threadId).Execute()); } catch (Exception Ex) { throw new Exception("Ocurrió un error: " + Ex.Message, Ex); } }
public async Task GetUnreadEmailsFromGmailAsync() { 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 }); var emailThreads = service.Users.Threads.List(SERVICE_ACCOUNT_EMAIL); // Get emails only form inbox which are unread var labels = new Google.Apis.Util.Repeatable <string>(new List <string> { "INBOX", "UNREAD" }); emailThreads.LabelIds = labels; emailThreads.IncludeSpamTrash = false; emailThreads.MaxResults = 5000; var emailThreadResult = await emailThreads.ExecuteAsync(); if (emailThreadResult != null && emailThreadResult.Threads != null && emailThreadResult.Threads.Any()) { foreach (var thread in emailThreadResult.Threads) { var data = await service.Users.Threads.Get(SERVICE_ACCOUNT_EMAIL, thread.Id).ExecuteAsync(); var gmailId = data?.Id; if (data != null) { foreach (var emailInfoResponse in data.Messages) { if (emailInfoResponse != null) { string body = string.Empty; var dateReceived = emailInfoResponse.Payload?.Headers?.FirstOrDefault(s => s.Name == "Date")?.Value ?? string.Empty; var from = emailInfoResponse.Payload?.Headers?.FirstOrDefault(s => s.Name == "From") ?.Value ?? string.Empty; var subject = emailInfoResponse.Payload?.Headers?.FirstOrDefault(s => s.Name == "Subject") ?.Value ?? string.Empty; var emailDto = new EmailDTO { Subject = subject, Body = body, DateReceived = dateReceived, From = from, GmailEmailId = gmailId, }; var parts = emailInfoResponse.Payload?.Parts; double totalAttachmentsSizeInMb = 0; var attachmentsToAdd = new List <EmailAttachmentDTO>(); if (parts != null) { if (parts.First().MimeType.Contains("text/plain")) // Email do not have attachments { emailDto.Body = parts.First().Body.Data; emailDto.AttachmentsTotalSizeInMB = 0; emailDto.TotalAttachments = 0; } else // Email have attachment(s) { emailDto.Body = parts.First().Parts.First().Body.Data; var attachments = parts.Skip(1).ToList(); foreach (var attachment in attachments) { var attachmentName = attachment.Filename; double attachmentSize; try { attachmentSize = double.Parse(attachment.Body.Size.ToString()); } catch (Exception) { attachmentSize = 0.0; } var emailAttachmentDto = new EmailAttachmentDTO { FileSizeInMb = attachmentSize, AttachmentName = attachmentName }; totalAttachmentsSizeInMb += attachmentSize; attachmentsToAdd.Add(emailAttachmentDto); } totalAttachmentsSizeInMb /= (1024 * 1024); emailDto.AttachmentsTotalSizeInMB = totalAttachmentsSizeInMb; emailDto.TotalAttachments = attachments.Count; } } var id = await this.emailService.CreateAsync(emailDto); if (attachmentsToAdd.Count > 0) { foreach (var attachment in attachmentsToAdd) { attachment.ReceivedEmailId = id; await this.emailAttachmentService.AddAttachmentAsync(attachment); } } var markAsReadRequest = new ModifyThreadRequest { RemoveLabelIds = new[] { "UNREAD" } }; await service.Users.Threads.Modify(markAsReadRequest, SERVICE_ACCOUNT_EMAIL, thread.Id) .ExecuteAsync(); } } } } } }
public static void StaticRun() { UserCredential credential; using (var stream = new FileStream("creds.json", FileMode.Open, FileAccess.Read)) { string credPath = MainClass.location + "gcreds"; 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, }); var inboxlistRequest = service.Users.Messages.List(UserMail); inboxlistRequest.LabelIds = LabelId; inboxlistRequest.Q = "is:unread"; inboxlistRequest.IncludeSpamTrash = false; //get our emails var emailListResponse = inboxlistRequest.Execute(); if (emailListResponse != null && emailListResponse.Messages != null) { //loop through each email and get what fields you want... foreach (var email in emailListResponse.Messages) { var emailInfoRequest = service.Users.Messages.Get(UserMail, email.Id); var emailInfoResponse = emailInfoRequest.Execute(); MainClass.positionContracts = MainClass.getPosition(); if (emailInfoResponse != null) { string mData = emailInfoResponse.Snippet; if (mData.Contains(MainClass.pair) && mData.Contains(sellTrigger) && (MainClass.positionContracts > 0 || MainClass.positionContracts == 0) && lastAlert != "Sell") { MainClass.log(emailInfoResponse.Snippet); MainClass.log("Short: " + MainClass.pair); string json = MainClass.bitMEXApi.MarketOrder(MainClass.pair, "Sell", Math.Abs(MainClass.positionContracts) + MainClass.qtdyContacts, "Tradingview Short"); if (json.ToLower().IndexOf("error") >= 0 || json.ToLower().IndexOf("canceled") >= 0) { if (json.ToLower().IndexOf("overload") >= 0 && Math.Abs(MainClass.positionContracts) > 0) {/* In case of overload, close the position to prevent losses*/ MainClass.log("System is on overload, trying to close position to prevent losses"); MainClass.log(MainClass.bitMEXApi.MarketClose(MainClass.pair, "Sell")); } return; } lastAlert = "Sell"; } else if (mData.Contains(MainClass.pair) && mData.Contains(buyTrigger) && (MainClass.positionContracts < 0 || MainClass.positionContracts == 0) && lastAlert != "Buy") { MainClass.log(emailInfoResponse.Snippet); MainClass.log("Long: " + MainClass.pair); string json = MainClass.bitMEXApi.MarketOrder(MainClass.pair, "Buy", Math.Abs(MainClass.positionContracts) + MainClass.qtdyContacts, "Tradingview Long"); if (json.ToLower().IndexOf("error") >= 0 || json.ToLower().IndexOf("canceled") >= 0) { if (json.ToLower().IndexOf("overload") >= 0 && Math.Abs(MainClass.positionContracts) > 0) {/* In case of overload, close the position to prevent losses*/ MainClass.log("System is on overload, trying to close position to prevent losses"); MainClass.log(MainClass.bitMEXApi.MarketClose(MainClass.pair, "Buy")); } return; } lastAlert = "Buy"; } /* we'll do some crap here*/ var markAsReadRequest = new ModifyThreadRequest { RemoveLabelIds = new[] { "UNREAD" } }; var markRead = service.Users.Threads.Modify(markAsReadRequest, UserMail, emailInfoResponse.ThreadId); markRead.Execute(); } } } }