public bool CheckIncomingMessages(string mailTitle, string contactEmail) { UserCredential credential; using (FileStream stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, GmailOps.Scopes, "*****@*****.**", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } GmailService service = new GmailService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Gmail API Quickstart" }); List <Message> messageList = GmailOps.ListMessages(service, "me", "subject: " + mailTitle); foreach (Message message in messageList) { Message fullMessage = GmailOps.GetMessage(service, "me", message.Id); MessagePartHeader messageInfo = fullMessage.Payload.Headers.FirstOrDefault((MessagePartHeader x) => x.Name == "Delivered-To"); if (messageInfo != null && string.Equals(messageInfo.Value, contactEmail)) { return(true); } } return(false); }
private static string GetSubjectText(ICollection <MessagePartHeader> headers) { const string SubjectKey = "Subject"; MessagePartHeader subjectHeader = headers.FirstOrDefault(header => header.Name.Equals(SubjectKey)); return(subjectHeader?.Value); }
public void SendMessage(string recepient, string subject, string body) { if (service == null) { if (GMailConnect() == false || service == null) { MessageBox.Show("Ошибка отправки сообщения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } string userMail = google.getUserEmailAddress(); //MailMessage message = new MailMessage(userMail, recepient, subject, body); GMailMessage email = new GMailMessage(); email.Payload = new MessagePart(); email.Payload.Body = new MessagePartBody(); email.Payload.Body.Data = body; email.Payload.Headers = new List <MessagePartHeader>(); MessagePartHeader headerTo = new MessagePartHeader(); MessagePartHeader headerFrom = new MessagePartHeader(); MessagePartHeader headerSubject = new MessagePartHeader(); headerTo.Name = "To"; headerTo.Value = userMail;//recepient; headerFrom.Name = "From"; headerFrom.Value = userMail; headerSubject.Name = "Subject"; headerSubject.Value = "Счет за выполненные заказы"; email.Payload.Headers.Add(headerTo); email.Payload.Headers.Add(headerFrom); email.Payload.Headers.Add(headerSubject); email.Payload.MimeType = "text/plain"; try { service.Users.Messages.Send(email, userId).Execute(); } catch (Exception e) { MessageBox.Show("An error occurred: " + e.Message); } return; }
private static void Main(string[] args) { UserCredential credential; using (FileStream stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Program.Scopes, "*****@*****.**", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } GmailService service = new GmailService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Gmail API Quickstart" }); List <Message> messageList = Program.ListMessages(service, "me", "subject: " + mailTitle); foreach (Message message in messageList) { Message fullMessage = Program.GetMessage(service, "me", message.Id); MessagePartHeader messageInfo = fullMessage.Payload.Headers.FirstOrDefault((MessagePartHeader x) => x.Name == "Delivered-To"); if (messageInfo != null && string.Equals(messageInfo.Value, contactEmail)) { string bodyData = fullMessage.Payload.Body.Data.Replace("-", "+").Replace("_", "/"); byte[] data64Base = Convert.FromBase64String(bodyData); string htmlCode = Encoding.UTF8.GetString(data64Base); Regex linkParser = new Regex("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", RegexOptions.IgnoreCase | RegexOptions.Compiled); foreach (object link in linkParser.Matches(htmlCode)) { if (link.ToString().Contains(enviorment)) { string ret = link.ToString(); //return link.ToString(); } } } } //return null; }
/* TODO: Refactor to smaller functions * Checks if the email needs to be parsed for Door Dash or GrubHub, * and saves the order to file for reference */ private static Order HandleMessage(string messageId) { Debug.WriteLine("Handling message: " + messageId); bool isGrubHubOrder = false; string base64Input = null; //the input to be converted to base64url encoding format string fileName = null; //the file name without the complete path string storageDir = null; //the file saving directory string filePath = null; //the full path to the file var emailResponse = GetMessage(service, userId, messageId); if (emailResponse == null) { Debug.WriteLine("Message deleted, returning"); return(null); } var headers = emailResponse.Payload.Headers; MessagePartHeader dateHeader = headers.FirstOrDefault(item => item.Name == "Received"); MessagePartHeader fromHeader = headers.FirstOrDefault(item => item.Name == "From"); DateTime dateTime = ParseDateTime(dateHeader.Value); string senderAddress = fromHeader.Value; //Check if the email is from GrubHub if (fromHeader.Value == "*****@*****.**") { Debug.WriteLine("Email Type: GrubHub"); isGrubHubOrder = true; try { var body = emailResponse.Payload.Body.Data; base64Input = body; fileName = messageId + ".html"; storageDir = GrubHubDir; } catch (Exception e) { Debug.WriteLine(e.Message); } //Otherwise check if the email is from DoorDash } else if (fromHeader.Value == @"DoorDash <*****@*****.**>") { Debug.WriteLine("Email Type: DoorDash"); try { var attachId = emailResponse.Payload.Parts[1].Body.AttachmentId; //Need to do another API call to get the actual attachment from the attachment id MessagePartBody attachPart = GetAttachment(service, userId, messageId, attachId); base64Input = attachPart.Data; fileName = messageId + ".pdf"; storageDir = DoorDashDir; }catch (Exception e) { Debug.WriteLine(e.Message); } //The email is refers to a cancelled GrubHub order, so set the associated OrderCons' status to cancelled } else if (fromHeader.Value == "*****@*****.**") { Debug.WriteLine("From [email protected]"); MessagePartHeader subjectHeader = headers.FirstOrDefault(item => item.Name == "Subject"); string orderNum = subjectHeader.Value.Split(' ')[1]; //gets orderNum from ("Order" {orderNum} "Cancelled") Debug.WriteLine("OrderNum: " + orderNum); if (form1.InvokeRequired) { form1.Invoke((MethodInvoker) delegate { form1.SetOrderToCancelled(orderNum); }); } else { form1.SetOrderToCancelled(orderNum); } return(null); //The email is irrelevant } else { Debug.WriteLine("Not an order, returning"); return(null); } byte[] data = FromBase64ForUrlString(base64Input); filePath = Path.Combine(storageDir, fileName); //Saves the order to file if it doesn't exist if (!File.Exists(filePath)) { Debug.WriteLine("Writing new file: " + fileName); File.WriteAllBytes(filePath, data); } else { Debug.WriteLine("File already exists: " + fileName); } Debug.WriteLine("----------------------"); if (isGrubHubOrder) { GrubHubParser grubHubParser = new GrubHubParser(); string decodedBody = Encoding.UTF8.GetString(data); Order order = grubHubParser.ParseOrder(decodedBody, dateTime, messageId); if (DebugPrint) { order.PrintOrder(); } return(order); } else { DoorDashParser doorDashParser = new DoorDashParser(); List <string> lines = doorDashParser.ExtractTextFromPDF(filePath, messageId); Order order = doorDashParser.ParseOrder(lines, dateTime, messageId); string s = emailResponse.Payload.Parts[0].Parts[1].Body.Data; byte[] data2 = FromBase64ForUrlString(emailResponse.Payload.Parts[0].Parts[1].Body.Data); string decodedBody = Encoding.UTF8.GetString(data2); doorDashParser.ParseConfirmURL(order, decodedBody); if (DebugPrint) { order.PrintOrder(); } return(order); } }