// cada acion de requerimento pueede tener o no Adjuntos e hacer lo getfiles private List <string> GetFiles(GmailService service, IList <MessagePart> parts, string messageId) { LogStartStep(51); try { List <string> files = new List <string>(); foreach (MessagePart part in parts) { if (!String.IsNullOrEmpty(part.Filename) && part.Filename.Substring(part.Filename.Length - 3, 3) != "gif") { String attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments.Get(_userId, messageId, attId).Execute(); String attachData = Regex.Replace(attachPart.Data, "-", "+"); attachData = Regex.Replace(attachData, "_", "/"); attachData = Regex.Replace(attachData, "=", "/"); byte[] data = Convert.FromBase64String(attachData); File.WriteAllBytes(Path.Combine(_diretorio, part.Filename), data); files.Add(Path.Combine(_diretorio, part.Filename)); } } return(files); } catch (Exception ex) { throw new Exception("No fue posible guardar los adjuntos" + ex.Message); } }
public void GoogleService_Gmail_GetAttachments() { //arrange string userId = string.Empty; _initSvc.User = userId; //act ListThreadsResponse lThread = _googleSvc.GetThreadList(_initSvc, userId); //assert Thread firstThread = lThread.Threads[0]; if (firstThread.Messages != null) { foreach (Message message in firstThread.Messages) { foreach (MessagePart part in message.Payload.Parts) { if (!string.IsNullOrEmpty(part.Filename)) { string attId = part.Body.AttachmentId; MessagePartBody attachPart = _googleSvc.GetMessageAttachment(_initSvc, userId, message.Id, attId); // Converting from RFC 4648 base64-encoding // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history string attachData = attachPart.Data.Replace('-', '+'); attachData = attachData.Replace('_', '/'); byte[] data = Convert.FromBase64String(attachData); } } } } }
private byte[] GetAttachment(string messageId, string attachmentId) { var request = _service.Users.Messages.Attachments.Get("me", messageId, attachmentId); MessagePartBody part = request.Execute(); return(DecompressToBytes(part.Data)); }
public async Task <IEnumerable <int> > GetAttachmentsAsync(Message message) { var parts = message.Payload.Parts; var totalSize = 0; var countOfAttachmenets = 0; foreach (MessagePart part in parts) { if (!string.IsNullOrEmpty(part.Filename)) { var attId = part.Body.AttachmentId; MessagePartBody attachPart = await this.emailService.Users.Messages.Attachments.Get(EmailConstants.EMAIL_ADDRESS, message.Id, attId).ExecuteAsync(); if (attachPart != null) { totalSize += (int)attachPart.Size; countOfAttachmenets++; } } } return(new List <int> { totalSize, countOfAttachmenets }); }
// make method async EAttachment getAttachmentData(Email mail, string attachmentId, string filename) { EAttachment attachment = null; MessagePartBody attachPart = _service.Users.Messages.Attachments.Get("me", mail.MailId, attachmentId).Execute(); byte[] attachmentData = CommonFunctions.FromBase64ForString(attachPart.Data); StorageService.Storage storageService = new StorageService.Storage("Email/" + mail.MailId); EStorageRequest request = new EStorageRequest { FileName = filename, isSaveLocal = true }; BaseReturn <EStorageResponse> storageResponse = storageService.BinaryUpload(request, attachmentData); attachment = new EAttachment { AttachmentId = attachmentId, Filename = filename, localUrl = storageResponse.Data.LocalFilePath, CloudUrl = storageResponse.Data.BucketFilePath, Data = attachPart != null ? attachmentData : null }; return(attachment); }
public static void GetAttachments(GmailService service, String userId, String messageId, String outputDir) { try { Message message = service.Users.Messages.Get(userId, messageId).Execute(); 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(userId, messageId, attId).Execute(); // 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); File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data); } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
/// <summary> /// get attachments from message /// </summary> /// <param name="service"></param> /// <param name="userId"></param> /// <param name="messageId"></param> /// <param name="outputDir"></param> public static List <Attachment> GetAttachments(GmailService service, Message message, String userId, String messageId, bool save) { List <Attachment> attac = new List <Attachment>(); IList <MessagePart> parts = message.Payload.Parts; if (parts != null) { foreach (MessagePart part in parts) { if (!String.IsNullOrEmpty(part.Filename)) { String attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments.Get(userId, messageId, attId).Execute(); var converte = ConverteBase64Google(attachPart.Data); var path = ""; if (save) { path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\" + messageId + "\\"; Directory.CreateDirectory(path); File.WriteAllBytes(path + part.Filename, converte); } var attachment = new Attachment(part.Filename, path, converte, part.MimeType); attac.Add(attachment); } } } return(attac); }
/// <summary> /// Get and store attachment from Message with given ID. /// </summary> /// <param name="service">Gmail API service instance.</param> /// <param name="userId">User's email address. The special value "me" /// can be used to indicate the authenticated user.</param> /// <param name="messageId">ID of Message containing attachment.</param> public static string GetAttachments(GmailService service, String userId, Message message) { try { 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(userId, message.Id, attId).Execute(); // 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); return(System.Text.Encoding.Default.GetString(data)); } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } return(null); }
async Task SaveAttachement(string messageId, FileConfiguration config, Func <MessagePart, bool> fileNameFilter) { Message message = await service.Users.Messages.Get(Constants.Me, messageId).ExecuteAsync(); List <MessagePart> parts = message.Payload.Parts.Where(fileNameFilter).ToList(); if (parts.Count >= 1) { string attId = parts[0].Body.AttachmentId; MessagePartBody attachPart = await service.Users.Messages.Attachments.Get(Constants.Me, messageId, attId).ExecuteAsync(); // 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); string destinationFilePath = FileOperation.PrepareDestination(config); File.WriteAllBytes(destinationFilePath, data); } else { throw new InvalidProgramException("Configuration or implementation is invalid. Query result contains some emails with attachements, but no attachements available in message body."); } }
/// <summary> /// Get and store pdf files attachment from Message /// </summary> /// <param name="userId">User's email address. The special value "me" can be used to indicate the authenticated user.</param> /// <param name="messageId">ID of Message containing attachment.</param> /// <param name="outputDir">Directory used to store attachments.</param> public void GetPdfAttachments(Message message, string outputDir) { try { if (message.Payload.Parts != null) { IList <MessagePart> parts = message.Payload.Parts; foreach (MessagePart part in parts) { if (!String.IsNullOrEmpty(part.Filename) && part.MimeType == "application/pdf") { String attId = part.Body.AttachmentId; if (attId != null) { MessagePartBody attachPart = GmailService.Users.Messages.Attachments.Get("me", message.Id, attId).Execute(); // 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); File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data); } } } } } catch (Exception e) { Console.WriteLine($"An error occurred: {e.Message} - [{message.Id}]"); } }
public MessagePartBody GetMessageAttachment(Initializer initializer, string userId, string messageId, string attachmentId) { GmailService svc = new GmailService(CreateInitializer(initializer)); MessagePartBody attachPart = svc.Users.Messages.Attachments.Get(userId, messageId, attachmentId).Execute(); return(attachPart); }
public string[] Download(string AttId) { MessagePartBody Attachment = Operations.Gmail.Connect.service.Users.Messages.Attachments.Get("me", Operations.Content.Message.ID, AttId).Execute(); // Converting from RFC 4648 base64 to base64url encoding string[] Result = new string[2]; Result[0] = Attachment.Data.Replace('-', '+').Replace('_', '/'); Result[1] = Attachment.Size.ToString(); return(Result); }
/// <summary> /// Get and store attachment from Message with given ID. /// </summary> /// <param name="service">Gmail API service instance.</param> /// <param name="userId">User's email address. The special value "me" /// can be used to indicate the authenticated user.</param> /// <param name="messageId">ID of Message containing attachment.</param> /// <param name="outputDir">Directory used to store attachments.</param> static void GetAttachments(GmailService service, String userId, String messageId, String outputDir) { try { Message message = service.Users.Messages.Get(userId, messageId).Execute(); var 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(userId, messageId, attId).Execute(); // 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); File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data); } } // сохраним ID сообщения, чтобы не выгружать его в последующем string listfile = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location) + ".list"; if (!File.Exists(listfile)) { File.AppendAllText(listfile, messageId); } else { File.AppendAllText(listfile, Environment.NewLine + messageId); } } catch (Exception e) { string error = e.Message; if (e.InnerException != null) { error = e.InnerException.Message; } string logfile = Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location) + ".log"; WriteErrorToLog(logfile, e.ToString()); Console.WriteLine(e.Message); } }
/// <summary> /// Decodes the attachment data from Base64 to string. /// </summary> /// <param name="attachment">The attachment.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">attachment</exception> /// <exception cref="InvalidDataException">There was no data for the Attachment Id: {attachment.AttachmentId}</exception> private string DecodeAttachmentData(MessagePartBody attachment) { if (attachment is null) { throw new ArgumentNullException(nameof(attachment)); } var dataExisits = attachment.Data != null; if (dataExisits is true) { return(Tools.Base64ToString(attachment.Data)); } throw new InvalidDataException($"There was no data for the Attachment Id: {attachment.AttachmentId}"); }
private byte[] RetrieveFileById(string messageId, string attachmentId) { MessagePartBody attachment = service.Users.Messages.Attachments .Get("me", messageId, attachmentId).Execute(); if (attachment != null) { StringBuilder data = new StringBuilder(attachment.Data); // Convert from RFC 4648 base64urlsafe encoding to base64 // see http://en.wikipedia.org/wiki/Base64#Implementations_and_history data.Replace('-', '+').Replace('_', '/'); return(Convert.FromBase64String(data.ToString())); } Trace.WriteLine($"Failed to fetch attachment for message id: {messageId} and attachment id: {attachmentId}"); return(null); }
public string GetAttachments(GmailService service, String userId, String messageId, String outputDir, Message message) { string attachmentMessage = ""; try { 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(userId, messageId, attId).Execute(); String attachData = attachPart.Data.Replace('-', '+'); attachData = attachData.Replace('_', '/'); byte[] data = Convert.FromBase64String(attachData); string[] fileType = part.Filename.Split('.'); string[] fileName = userId.Split('@'); int i = 0; string outputDirectory = outputDir + fileName[0] + "." + fileType[fileType.Length - 1]; while (File.Exists(outputDirectory)) { i = i + 1; outputDirectory = outputDir + fileName[0] + "(" + i + ")" + "." + fileType[fileType.Length - 1]; } File.WriteAllBytes(Path.Combine(outputDirectory, ""), data); attachmentMessage += userId + "'s " + "file has been saved as " + outputDirectory + "\n"; } } } catch (Exception e) { Console.WriteLine(@"An error occurred: " + e.Message); } return(attachmentMessage); }
public async Task <IActionResult> GetMsgBody(string EmailId) // Show Email Body JavaScript { string UserEmail = User.FindFirst(c => c.Type == ClaimTypes.Email).Value; var service = GetService(); var emailInfoRequest = service.Users.Messages.Get(UserEmail, EmailId); emailInfoRequest.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw; Message message = await service.Users.Messages.Get(UserEmail, EmailId).ExecuteAsync(); A.body = message.Snippet; byte[] data = null; int i = 0; IList <MessagePart> parts = message.Payload.Parts; String[] attach_name = new string[parts.Count - 1]; object[] dataArr = new object[parts.Count - 1]; foreach (MessagePart part in parts) { if (!String.IsNullOrEmpty(part.Filename)) { String attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments.Get(UserEmail, EmailId, attId).Execute(); attach_name[i++] += part.Filename; data = Decode(attachPart.Data); //System.IO.File.WriteAllBytes(System.IO.Path.Combine(@"C:\Users\Admin\source\repos\Gmail_API\Get_Attachment", part.Filename), data); } } if (A.body == String.Empty) { A.body = "There is no message text... The Content is EMPTY!"; } ViewBag.data = data; ViewBag.name = attach_name; //PartialView("~/Views/Home/Index.cshtml", ViewBag.name); return(PartialView("~/Views/Google/MsgBody.cshtml", A.body)); }
/// <summary> /// Decodes useful information from the Emails in the queue /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="ElapsedEventArgs"/> instance containing the event data.</param> /// <exception cref="NotImplementedException"></exception> private async void ParsePayLoadFromEmailsQueue_ElapsedAsync(object sender, EventArgs e) { try { _payloadParser.Stop(); // Read all the Queued emails while (LabelSpecificEmails.Count != 0) { var message = LabelSpecificEmails.Dequeue(); MessagePartBody attachment = await GetAttachment(message, AttachmentFormat.CSV_FORMAT); string readableData = DecodeAttachmentData(attachment); var book = new Book(readableData); Book bookRead = ViewModel.BooksRead.Where(s => s == book).FirstOrDefault(); if (bookRead == null) { book.UpdateNotes(readableData, false); ViewModel.BooksRead.Add(book); ViewModel.CreateAndUpdateJsonDataBase(); } else { bookRead.UpdateNotes(readableData, true); } } } catch (Exception exc) { LogError(exc); } finally { _payloadParser.Start(); } }
public bool GetAttachments(GmailService service, string userId, string messageId) { bool flag = false; //string outputDir = "temp"; try { Message message = service.Users.Messages.Get(userId, messageId).Execute(); if (message.Payload.Parts != null) { 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(userId, messageId, attId).Execute(); String attachData = attachPart.Data.Replace('-', '+'); attachData = attachData.Replace('_', '/'); byte[] data = Convert.FromBase64String(attachData); string filetmp = Path.Combine(pathinit, part.Filename); File.WriteAllBytes(filetmp, data); attach.file = part.Filename; attach.source = filetmp; attach.CheckPath(); flag = attach.Move(); } } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return(flag); }
/* 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); } }
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(); }
public static bool GetAttachments(GmailService service, String userId, String messageId, String outputDir) { //string txt_file_dir = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(), txt_file_name); //string textContent = File.ReadAllText(txt_file_dir); //string createText = "Hello and Welcome" + Environment.NewLine; //File.WriteAllText(path, createText); //Console.WriteLine("An error occurred: " + e.Message); //try //{ // return service.Users.Messages.Modify(mods, userId, messageId).Execute(); //} //catch (Exception e) //{ // Console.WriteLine("An error occurred: " + e.Message); //} string txt_file_dir = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(), txt_file_name); string createText = null; try { Message message = service.Users.Messages.Get(userId, messageId).Execute(); 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(userId, messageId, attId).Execute(); // 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); if (Path.GetExtension(part.Filename) == ".pdf" && part.Filename.Contains("bon-fournisseur")) { string readText = File.ReadAllText(txt_file_dir); createText = readText; string[] fileListContent = readText.Split(new[] { Environment.NewLine }, StringSplitOptions.None); string filePath = Path.Combine(outputDir, part.Filename); string order_name = part.Filename.Replace("bon-fournisseur-", "").Replace(".pdf", "").Trim(); bool order_check_flag = false; foreach (string t_item in fileListContent) { if (t_item == order_name) { order_check_flag = true; } } if (!order_check_flag) { // Download pdf file File.WriteAllBytes(filePath, data); fileList.Add(filePath); // Change Unread label // Add new order line in file createText = readText + order_name + Environment.NewLine; } File.WriteAllText(txt_file_dir, createText); DeleteLabel(service, "me", "UNREAD", messageId); } } } //File.WriteAllText(txt_file_dir, createText); //return fileList; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); //return null; } return(true); }
public static Email ToEmail(this Message message, GmailService service) { var email = new Email(); if (message != null) { email.Id = message.Id; foreach (var header in message.Payload.Headers) { switch (header.Name) { case "Date": email.Date = header.Value != null ? (DateTime?)DateTime.Parse(header.Value) : null; break; case "From": email.From = header.Value; break; case "Subject": email.Subject = header.Value; break; } } if (email.Date != null && !string.IsNullOrWhiteSpace(email.From)) { if (message.Payload.Parts == null && message.Payload.Body != null) { email.Body = decodeBase64String(message.Payload.Body.Data); } else { email.Body = getNestedBodyParts(message.Payload.Parts, string.Empty); } IList <MessagePart> parts = message.Payload.Parts; foreach (MessagePart part in parts) { if (!String.IsNullOrEmpty(part.Filename)) { var attachment = new Attachment(); attachment.Id = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments .Get("me", message.Id, attachment.Id) .Execute(); // 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('_', '/'); attachment.File = Convert.FromBase64String(attachData); attachment.Name = part.Filename; email.Attachments.Add(attachment); } } } return(email); } return(null); }
public async Task <OperationResult> Read(string token) { var pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "RentableItemBaseSettings:Token"); if (pluginConfiguration == null) { return(new OperationResult(false)); } if (token == pluginConfiguration.Value) { UserCredential credential; pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "RentableItemBaseSettings:GmailCredentials"); GoogleClientSecrets secrets = NewtonsoftJsonSerializer.Instance.Deserialize <GoogleClientSecrets>(pluginConfiguration.Value); pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "RentableItemBaseSettings:GmailUserName"); string gmailUserName = pluginConfiguration.Value; pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "RentableItemBaseSettings:MailFrom"); string mailFrom = pluginConfiguration.Value; pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "RentableItemBaseSettings:GmailEmail"); string gmailEmail = pluginConfiguration.Value; pluginConfiguration = await _dbContext.PluginConfigurationValues.SingleOrDefaultAsync(x => x.Name == "RentableItemBaseSettings:SdkeFormId"); int eFormId = int.Parse(pluginConfiguration.Value); try { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets.Secrets, Scopes, gmailUserName, CancellationToken.None, new FileDataStore(credPath, true)).Result; var service = new GmailService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = ApplicationName }); var emailListRequest = service.Users.Messages.List(gmailEmail); emailListRequest.LabelIds = "INBOX"; emailListRequest.IncludeSpamTrash = false; emailListRequest.Q = $"from:{mailFrom}"; emailListRequest.MaxResults = 1; var emailListResponse = await emailListRequest.ExecuteAsync(); if (emailListResponse != null && emailListResponse.Messages != null) { foreach (var email in emailListResponse.Messages) { var emailInfoRequest = service.Users.Messages.Get(gmailEmail, email.Id); var emailInfoResponse = await emailInfoRequest.ExecuteAsync(); if (emailInfoResponse != null) { IList <MessagePart> parts = emailInfoResponse.Payload.Parts; foreach (var part in parts) { if (!string.IsNullOrEmpty(part.Filename)) { string attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments .Get(gmailEmail, email.Id, attId).Execute(); string attachData = attachPart.Data.Replace("-", "+"); attachData = attachData.Replace("_", "/"); byte[] data = Convert.FromBase64String(attachData); var bytesAsString = Encoding.Default.GetString(data); string[] rawFile = bytesAsString.Split("\n"); var importList = rawFile.Skip(2); string[] list = importList.ToArray(); var headers = rawFile[0].Split(","); foreach (string s in list) { string[] lSplit = s.Split("\",\""); if (lSplit.Length == 8) { Contract contract = null; Customer customer = null; ContractRentableItem contractRentableItem = null; try { customer = _customerDbContext.Customers.SingleOrDefault(x => x.CompanyName == lSplit[1] || x.ContactPerson == lSplit[1]); if (customer == null) { customer = new Customer { CompanyName = lSplit[1] }; await customer.Create(_customerDbContext); } } catch (Exception e) { Console.WriteLine(e); throw; } RentableItem rentableItem = null; try { rentableItem = _dbContext.RentableItem.SingleOrDefault(x => x.Brand == lSplit[2] && x.ModelName == lSplit[3] && x.RegistrationDate == DateTime.Parse(lSplit[4])); if (rentableItem == null) { rentableItem = new RentableItem { Brand = lSplit[2], ModelName = lSplit[3], RegistrationDate = DateTime.Parse(lSplit[4]), VinNumber = lSplit[5], eFormId = eFormId }; await rentableItem.Create(_dbContext); } } catch (Exception e) { Console.WriteLine(e); throw; } try { contract = _dbContext.Contract.SingleOrDefault(x => x.ContractNr == int.Parse(lSplit[0].Replace("\"", ""))); if (contract == null) { contract = new Contract { ContractNr = int.Parse(lSplit[0].Replace("\"", "")), ContractStart = DateTime.Parse(lSplit[6]), ContractEnd = DateTime.Parse(lSplit[7].Replace("\r", "").Replace("\"", "")), CustomerId = customer.Id, Status = 0 }; await contract.Create(_dbContext); } } catch (Exception e) { Console.WriteLine(e); throw; } try { contractRentableItem = _dbContext.ContractRentableItem.SingleOrDefault(x => x.ContractId == contract.Id && x.RentableItemId == rentableItem.Id); if (contractRentableItem == null) { contractRentableItem = new ContractRentableItem { ContractId = contract.Id, RentableItemId = rentableItem.Id }; await contractRentableItem.Create(_dbContext); } } catch (Exception e) { Console.WriteLine(e); throw; } } } } } } } } } catch (Exception e) { Console.WriteLine(e); throw; } } return(new OperationResult(true)); }
public void GetFile(string messageId, ref GRule gRule, Callback callback, Callback progressbar) { byte[] data = null; string filename = ""; var emailRequest = service.Users.Messages.Get("me", messageId); emailRequest.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full; var parts = emailRequest.Execute().Payload.Parts; if (parts != null) { foreach (var part in parts) { if (!String.IsNullOrEmpty(part.Filename)) { callback(part.Filename); string[] strs = Regex.Split(part.Filename, "[.]+"); string type = String.Empty; if (String.IsNullOrEmpty(gRule.type)) { type = strs[strs.Length - 1]; } else { type = gRule.type; } if (type == strs[strs.Length - 1]) { ++counterAllFiles; String attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments.Get("me", messageId, attId).Execute(); String attachData = attachPart.Data.Replace('-', '+'); attachData = attachData.Replace('_', '/'); data = Convert.FromBase64String(attachData); string name = Path.Combine(gRule.path, part.Filename); if (File.Exists(name)) { File.Delete(name); } using (FileStream fileStream = new FileStream(name, FileMode.OpenOrCreate, FileAccess.Write)) { fileStream.Seek(0, SeekOrigin.Begin); int d = data.Length; int offset = 0; for (offset = 0; (data.Length - offset) > 500000; offset += 500000) { int l = data.Length - offset; fileStream.Write(data, offset, 500000); fileStream.Flush(); } fileStream.Write(data, offset, data.Length - offset); fileStream.Close(); } //File.WriteAllBytes(Path.Combine(gRule.path, part.Filename), data); filename = part.Filename; GDownloads gDownloads = new GDownloads(part.Filename, gRule.path, DateTime.Now); Act.FileParser.Add(GDownloads.pathfile, gDownloads); ++downloadFiles; } } } } gRule.lastMesId = messageId; ++processedMessages; progressbar(((processedMessages / allMessages) * 100)); //return filename; }
public static void ProcessMessage(GmailService service, String messageId) { try { Google.Apis.Gmail.v1.Data.Message message = GetMessage(service, _userId, messageId); string mailSubject = message.Payload.Headers.FirstOrDefault(x => x.Name.ToLower() == "subject").Value; //string sender = message.Payload.Headers.FirstOrDefault(x => x.Name.ToLower() == "from").Value;//.Replace("<", "").Replace(">", ""); string sender = message.Payload.Headers.FirstOrDefault(x => x.Name.ToLower() == "return-path").Value.Replace("<", "").Replace(">", ""); string receiver = message.Payload.Headers.FirstOrDefault(x => x.Name.ToLower() == "delivered-to").Value;//.Replace("<", "").Replace(">", ""); string msgId = message.Payload.Headers.FirstOrDefault(x => x.Name.ToLower() == "message-id").Value; //Get Lable Id for "Ab.Processed" Label abProcessedLable = GetLabelByName(service, _processedLbl); if (abProcessedLable == null) // Create New Lable if Not created yet { abProcessedLable = CreateLabel(service, _processedLbl); } // Extract Domain & Patient string strErrorMsg = ""; string domain, patientNumber = string.Empty; string strRegexSubject = Regex.Replace(mailSubject, "[,|:|;]", "?"); var subjectArray = strRegexSubject.Split('?'); if (subjectArray == null || subjectArray.Length == 0) { strErrorMsg = "Mail subject not provided OR Empty mail subject."; } else if (subjectArray.Length < 3) { strErrorMsg = "Invalid Mail Subject: " + mailSubject; } else { domain = subjectArray[1].Replace(")", "").Replace("(", "").Replace("]", "").Replace("[", "").Trim(); patientNumber = subjectArray[2].Replace(")", "").Replace("(", "").Replace("]", "").Replace("[", "").Trim(); IList <MessagePart> attachments = message.Payload.Parts.Where(x => !string.IsNullOrEmpty(x.Filename)).ToList(); if (attachments != null) { foreach (MessagePart part in attachments) { string folderPath = _docRootDirectory + "/" + domain + "/Docfolder/" + patientNumber + "/"; string filePath = Path.Combine(folderPath, part.Filename); // TODO : Proccessing Mail & Save Attachment Logic if (string.IsNullOrEmpty(strErrorMsg)) { String attId = part.Body.AttachmentId; MessagePartBody attachPart = service.Users.Messages.Attachments.Get(_userId, messageId, attId).Execute(); String attachData = attachPart.Data.Replace('-', '+').Replace('_', '/'); byte[] data = Convert.FromBase64String(attachData); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } File.WriteAllBytes(filePath, data); } } } else { strErrorMsg = "Error: Attachment not found."; } //Mark mail as read MoifyMessage(service, _userId, messageId, new List <String>() { abProcessedLable.Id }, new List <String>() { "UNREAD", "INBOX" }); } // SEND FeedBack Success/Failure. string feedbackMailSubject = string.IsNullOrEmpty(strErrorMsg) ? ("Accepted: " + mailSubject) : ("Error: " + mailSubject); string feedbackMailBody = string.IsNullOrEmpty(strErrorMsg) ? "File Accepted" : strErrorMsg; SendFeedBackMail(sender, feedbackMailSubject, feedbackMailBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }