/// <summary> /// Writes the body of the MSG Appointment to html or text and extracts all the attachments. The /// result is return as a List of strings /// </summary> /// <param name="message"><see cref="Storage.Message"/></param> /// <param name="outputFolder">The folder where we need to write the output</param> /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param> /// <returns></returns> private List <string> WriteTask(Storage.Message message, string outputFolder, bool hyperlinks) { throw new NotImplementedException("Todo"); // TODO: Rewrite this code so that an correct task is written var result = new List <string>(); // Read MSG file from a stream // We first always check if there is a RTF body because appointments never have HTML bodies var body = message.BodyRtf; // If the body is not null then we convert it to HTML if (body != null) { var converter = new RtfToHtmlConverter(); body = converter.ConvertRtfToHtml(body); } // Determine the name for the appointment body var appointmentFileName = outputFolder + "task" + (body != null ? ".htm" : ".txt"); result.Add(appointmentFileName); // Write the body to a file File.WriteAllText(appointmentFileName, body, Encoding.UTF8); return(result); }
public void GetFiles() { if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } OpenFolder(); ArrFiles = Directory.GetFiles(sPath); var LFiles = ArrFiles.ToList(); foreach (string item in LFiles) { string Name; fList.Add(item); Id++; Name = Path.GetFileName(item); //Regex illegalInFileName = new Regex(@"[\\/:*?)(""<>|]"); //string myString = illegalInFileName.Replace(Name, ""); Storage.Message message = new Storage.Message(sPath + "\\" + Name); lstITM.Items.Add(new Item() { ID = Id, Name = Name, Date = Date, Message = message.ReceivedOn.ToString() }); } }
private static void ExtractAttachments(string path, string filename) { using (var msg = new Storage.Message(filename)) foreach (var attachment in msg.Attachments.OfType <Storage.Attachment>()) { if (attachment.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) { var outputFilename = Path.Combine(path, attachment.FileName); var data = attachment.Data; var dups = 0; while (File.Exists(outputFilename)) { if (File.ReadAllBytes(outputFilename).GetMD5() == data.GetMD5()) { break; } dups++; outputFilename = Path.Combine(path, Path.GetFileNameWithoutExtension(outputFilename) + $" ({dups}).pdf"); } File.WriteAllBytes(outputFilename, data); } } }
public MailInformation(Storage.Message message) { mSender = message.GetEmailSender(false, false).Trim(); mSubject = message.Subject; mHtmlBody = message.BodyHtml; mCreationDate = message.CreationTime; mAttachments = message.Attachments; string recipientItems = message.GetEmailRecipients(Storage.Recipient.RecipientType.To, false, false); if (recipientItems.Contains(";")) { mToRecipients = GetRecipients(recipientItems).ToList(); } else { mToRecipients = new List <string>() { recipientItems }; } recipientItems = message.GetEmailRecipients(Storage.Recipient.RecipientType.Cc, false, false); if (recipientItems.Contains(";")) { mCCRecipients = GetRecipients(recipientItems).ToList(); } else { mCCRecipients = new List <string>(); } }
/// <summary> /// Writes the body of the MSG StickyNote to html or text and extracts all the attachments. The /// result is return as a List of strings /// </summary> /// <param name="message"><see cref="Storage.Message"/></param> /// <param name="outputFolder">The folder where we need to write the output</param> /// <param name="hyperlinks">When true then hyperlinks are generated for the To, CC, BCC and attachments</param> /// <returns></returns> private List <string> WriteStickyNote(Storage.Message message, string outputFolder, bool hyperlinks) { var result = new List <string>(); string stickyNoteFile; var stickyNoteHeader = string.Empty; // Sticky notes only have RTF or Text bodies var body = message.BodyRtf; // If the body is not null then we convert it to HTML if (body != null) { var converter = new RtfToHtmlConverter(); body = converter.ConvertRtfToHtml(body); stickyNoteFile = outputFolder + (!string.IsNullOrEmpty(message.Subject) ? FileManager.RemoveInvalidFileNameChars(message.Subject) : "stickynote") + ".htm"; stickyNoteHeader = "<table style=\"width:100%; font-family: Times New Roman; font-size: 12pt;\">" + Environment.NewLine; if (message.SentOn != null) { stickyNoteHeader += "<tr style=\"height: 18px; vertical-align: top; \"><td style=\"width: 100px; font-weight: bold; \">" + LanguageConsts.StickyNoteDateLabel + ":</td><td>" + ((DateTime)message.SentOn).ToString(LanguageConsts.DataFormat) + "</td></tr>" + Environment.NewLine; } // Empty line stickyNoteHeader += "<tr><td colspan=\"2\" style=\"height: 18px; \"> </td></tr>" + Environment.NewLine; // End of table + empty line stickyNoteHeader += "</table><br/>" + Environment.NewLine; body = InjectHeader(body, stickyNoteHeader); } else { body = message.BodyText ?? string.Empty; // Sent on if (message.SentOn != null) { stickyNoteHeader += (LanguageConsts.StickyNoteDateLabel + ":") + ((DateTime)message.SentOn).ToString(LanguageConsts.DataFormat) + Environment.NewLine; } body = stickyNoteHeader + body; stickyNoteFile = outputFolder + (!string.IsNullOrEmpty(message.Subject) ? FileManager.RemoveInvalidFileNameChars(message.Subject) : "stickynote") + ".txt"; } // Write the body to a file File.WriteAllText(stickyNoteFile, body, Encoding.UTF8); result.Add(stickyNoteFile); return(result); }
/// <summary> /// Maps all the filled <see cref="Storage.Task"/> properties to the corresponding extended file attributes /// </summary> /// <param name="message">The <see cref="Storage.Message"/> object</param> /// <param name="propertyWriter">The <see cref="ShellPropertyWriter"/> object</param> private void MapTaskPropertiesToExtendedFileAttributes(Storage.Message message, ShellPropertyWriter propertyWriter) { // From propertyWriter.WriteProperty(SystemProperties.System.Message.FromAddress, message.Sender.Email); propertyWriter.WriteProperty(SystemProperties.System.Message.FromName, message.Sender.DisplayName); // Sent on propertyWriter.WriteProperty(SystemProperties.System.Message.DateSent, message.SentOn); // Subject propertyWriter.WriteProperty(SystemProperties.System.Subject, message.Subject); // Task startdate propertyWriter.WriteProperty(SystemProperties.System.StartDate, message.Task.StartDate); // Task duedate propertyWriter.WriteProperty(SystemProperties.System.DueDate, message.Task.DueDate); // Urgent propertyWriter.WriteProperty(SystemProperties.System.Importance, message.Importance); propertyWriter.WriteProperty(SystemProperties.System.ImportanceText, message.ImportanceText); // Status propertyWriter.WriteProperty(SystemProperties.System.Status, message.Task.StatusText); // Percentage complete propertyWriter.WriteProperty(SystemProperties.System.Task.CompletionStatus, message.Task.PercentageComplete); // Owner propertyWriter.WriteProperty(SystemProperties.System.Task.Owner, message.Task.Owner); // Categories propertyWriter.WriteProperty(SystemProperties.System.Category, message.Categories != null ? String.Join("; ", message.Categories) : null); // Companies propertyWriter.WriteProperty(SystemProperties.System.Company, message.Task.Companies != null ? String.Join("; ", message.Task.Companies) : null); // Billing information propertyWriter.WriteProperty(SystemProperties.System.Task.BillingInformation, message.Task.BillingInformation); // Mileage propertyWriter.WriteProperty(SystemProperties.System.MileageInformation, message.Task.Mileage); // Attachments var attachments = message.GetAttachmentNames(); if (string.IsNullOrEmpty(attachments)) { propertyWriter.WriteProperty(SystemProperties.System.Message.HasAttachments, false); propertyWriter.WriteProperty(SystemProperties.System.Message.AttachmentNames, null); } else { propertyWriter.WriteProperty(SystemProperties.System.Message.HasAttachments, true); propertyWriter.WriteProperty(SystemProperties.System.Message.AttachmentNames, attachments); } }
public void ReadAtt(string item) { Storage.Message message = new Storage.Message(item); string attch = message.GetAttachmentNames(); //CheckDate(attchs); aName = attch; }
public void ReadMail(Storage.Message message) { var LFiles = ArrFiles.ToList(); foreach (string item in LFiles) { } }
//COMPLETE private void HandleEmailFile(string file) { using (var message = new Storage.Message(file)) { var attachFolder = Directory.CreateDirectory($@"c:\temp\temp_msg_attachments_{DateTime.Now:MM-dd-yy hh-mm-ss tt}").FullName; SubmissionDetails details = ParseMessage(message.BodyText); foreach (Storage.Attachment attachment in message.Attachments) { File.WriteAllBytes(attachFolder + "\\" + attachment.FileName, attachment.Data); details.Files.Add(attachFolder + "\\" + attachment.FileName); } details.Sender = message.Sender.DisplayName; Globals.AttachmentFolder = attachFolder; HandleFiles(details); Directory.Delete(attachFolder, true); Globals.AttachmentFolder = ""; /*if (handed[0] + handed[1] == 0) * { * MessageBox.Show("Something went wrong. Please try again."); * return; * }*/ #if DEBUG #else message.Save($@"Z:\Archive\Field Data E-Mails\{details.JobNumbers[0]} {GetInitials(details.Sender)} {DateTime.Now:MM-dd-yy HH-mm-ss}.msg"); File.AppendAllLines($@"Z:\Archive\Field Data E-Mails Record Search.csv", new List <string> { $@"{details.JobNumbers[0]}, {details.Address}, {details.Purpose}, {GetInitials(details.Sender)}, {DateTime.Now:MM-dd-yy HH-mm-ss}, Z:\Archive\{details.JobNumbers[0]} {GetInitials(details.Sender)} {DateTime.Now:MM-dd-yy HH-mm-ss}.msg" }); #endif // TODO: Review post-process handling. /*var result = MessageBox.Show( * $"The e-mail has been parsed successfully! See below for the information.\n" + * $"Address: {details.Address}\n" + * $"Message Date: {message.ReceivedOn.Value}\n" + * $"Sender: {message.Sender.DisplayName} ({message.Sender.Email})\n" + * $"Purpose: {details.Purpose}\n" + * $"Total Files: {message.Attachments.Count}\n" + * $" Images: {handed[1]}\n" + * $" Other Files: {handed[0]}\n\n" + * $"Would you like to open the field data now?", * "Parsing Successful", * MessageBoxButtons.YesNo * ); * message.Dispose(); * if (result == DialogResult.Yes) * { * Process.Start.JobNumbers.GetPath(details.JobNumbers[0]) + "\\Field Data\\"); * }*/ } }
/// <summary> /// This function will read all the properties of an <see cref="Storage.Message"/> file and maps /// all the properties that are filled to the extended file attributes. /// </summary> /// <param name="inputFile">The msg file</param> public void SetExtendedFileAttributesWithMsgProperties(string inputFile) { MemoryStream memoryStream = null; try { // We need to read the msg file into memory because we otherwise can't set the extended filesystem // properties because the files is locked memoryStream = new MemoryStream(); using (var fileStream = File.OpenRead(inputFile)) fileStream.CopyTo(memoryStream); memoryStream.Position = 0; using (var shellFile = ShellFile.FromFilePath(inputFile)) { using (var propertyWriter = shellFile.Properties.GetPropertyWriter()) { using (var message = new Storage.Message(memoryStream)) { switch (message.Type) { case MessageType.Email: MapEmailPropertiesToExtendedFileAttributes(message, propertyWriter); break; case MessageType.AppointmentRequest: case MessageType.Appointment: case MessageType.AppointmentResponse: MapAppointmentPropertiesToExtendedFileAttributes(message, propertyWriter); break; case MessageType.Task: case MessageType.TaskRequestAccept: MapTaskPropertiesToExtendedFileAttributes(message, propertyWriter); break; case MessageType.Contact: MapContactPropertiesToExtendedFileAttributes(message, propertyWriter); break; case MessageType.Unknown: throw new NotSupportedException("Unsupported message type"); } } } } } finally { if (memoryStream != null) { memoryStream.Dispose(); } } }
//COMPLETE private void HandleOutlookItem(MemoryStream filestream) { Storage.Message message = new Storage.Message(filestream); //OutlookStorage.Message message = new OutlookStorage.Message(filestream); string fileName = $"temp_msg_{DateTime.Now:MM-dd-yy hh-mm-ss tt}.msg"; message.Save(@"c:\temp\" + fileName); message.Dispose(); HandleEmailFile(@"c:\temp\" + fileName); File.Delete(@"c:\temp\" + fileName); }
/// <summary> /// Search for matches in the in .MSG or .OFT files. /// </summary> /// <param name="fileName">The name of the file.</param> /// <param name="searchTerms">The terms to search.</param> /// <param name="matcher">The matcher object to determine search criteria.</param> /// <returns>The matched lines containing the search terms.</returns> private List <MatchedLine> GetMatchesInMsgOftFiles(string fileName, IEnumerable <string> searchTerms, Matcher matcher) { List <MatchedLine> matchedLines = new List <MatchedLine>(); using (var msg = new Storage.Message(fileName)) { string recipients = msg.GetEmailRecipients(RecipientType.To, false, false); string recipientsCc = msg.GetEmailRecipients(RecipientType.Cc, false, false); string headerInfo = string.Join(", ", new string[] { msg.Sender.Raw, msg.SentOn.GetValueOrDefault().ToString(), recipients, recipientsCc, msg.Subject }); matchedLines.AddRange(GetMatchesForHeader()); matchedLines.AddRange(GetMatchesForBody()); // Local function to get matches in the header part of mail. List <MatchedLine> GetMatchesForHeader() { int matchCounter = 0; foreach (string searchTerm in searchTerms) { MatchCollection matches = Regex.Matches(headerInfo, searchTerm, matcher.RegularExpressionOptions); // Use this match for getting the locations of the match. if (matches.Count > 0) { foreach (Match match in matches) { matchedLines.Add(new MatchedLine { MatchId = matchCounter++, Content = string.Format("{0}:\t{1}", Resources.Strings.Header, headerInfo), SearchTerm = searchTerm, FileName = fileName, LineNumber = 1, StartIndex = match.Index + Resources.Strings.Header.Length + 2, Length = match.Length }); } } } return(matchedLines); } // Local function to get matches in the body of mail. List <MatchedLine> GetMatchesForBody() { return(matcher.GetMatch(msg.BodyText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries), searchTerms)); } } return(matchedLines); }
/// <summary> /// Return information on one file /// </summary> /// <param name="pFileName"></param> /// <returns></returns> public MailInformation GetSingleMailItem(string pFileName) { if (File.Exists(pFileName)) { using (var message = new Storage.Message(pFileName)) { return(new MailInformation(message)); } } else { throw new FileNotFoundException(pFileName); } }
/// <summary> /// Reads all .msg files and extracts properties /// </summary> /// <param name="pFolder"></param> /// <returns></returns> public List <MailInformation> GetMailInformation(string pFolder) { List <MailInformation> items = new List <MailInformation>(); var files = new DirectoryInfo(pFolder).GetFiles("*.msg"); foreach (var file in files) { using (var message = new Storage.Message(file.FullName)) { items.Add(new MailInformation(message)); } } return(items); }
public ToxyEmail Parse() { ToxyEmail result = new ToxyEmail(); using (var stream = File.OpenRead(this.Context.Path)) using (var reader = new Storage.Message(stream)) { if (reader.Sender != null) { result.From = string.IsNullOrEmpty(reader.Sender.DisplayName) ? reader.Sender.Email : string.Format("{0}<{1}>", reader.Sender.DisplayName, reader.Sender.Email); } if (reader.Recipients.Count > 0) { foreach (var recipient in reader.Recipients) { string sRecipient = null; if (string.IsNullOrEmpty(recipient.DisplayName)) { sRecipient = recipient.Email; } else { sRecipient = string.Format("{0}<{1}>", recipient.DisplayName, recipient.Email); } if (recipient.Type == MsgReader.Outlook.Storage.Recipient.RecipientType.To) { result.To.Add(sRecipient); } else if (recipient.Type == MsgReader.Outlook.Storage.Recipient.RecipientType.Cc) { result.Cc.Add(sRecipient); } else if (recipient.Type == MsgReader.Outlook.Storage.Recipient.RecipientType.Bcc) { result.Bcc.Add(sRecipient); } } } result.Subject = reader.Subject; result.TextBody = reader.BodyText; result.HtmlBody = reader.BodyHtml; } return(result); }
/// <summary> /// Adds a date to the file name /// </summary> public void Rename() { DirCreate(); string Name; string NewName; lstITM.Items.Clear(); ArrFiles = Directory.GetFiles(sPath); var LFiles = ArrFiles.ToList(); foreach (string item in LFiles) { //Reads the email so it can get the proper subject and date Storage.Message message = new Storage.Message(item); string date = message.ReceivedOn.ToString(); Name = message.Subject; if (Name.Length < 1) { ReadAtt(item); Name = aName; } //Renames the file so it won't have any special characters //DateTime euDate = DateTime.ParseExact(date, "HH:mm", CultureInfo.InvariantCulture); DateTime euDate = DateTime.Parse(date); fName = Path.GetFileName(item); Regex illegalInFileName = new Regex(@"[\\/;/:*?)!#//¤%/$!,.&•(""<>|]"); string myString = illegalInFileName.Replace(euDate.ToString("HH:\\_mm_") + Name, ""); NewName = myString + Name; string source = sPath + "\\" + fName; string target = tPath + "\\" + myString; try { File.Copy(source, target + ".msg"); } catch (Exception e) { ErrMsg(e); } lstITM.Items.Add(new Item() { ID = Id, Name = NewName, Date = Date, Message = date }); Process.Start(tPath); } }
public void StorageFinaizerBehaviourTest() { int?SampleOperationWithDotNetsStreamReaders(System.IO.Stream stream) { //We will not call dispose here to keep the extern stream alive var reference = new System.IO.StreamReader(stream); return(reference.Read()); } int?OperationWithMsgReader(System.IO.Stream stream) { //We will not call dispose here to keep the extern stream alive var reference = new Storage.Message(stream); return(reference.Size); } using (var inputStream = System.IO.File.Open(System.IO.Path.Combine("SampleFiles", "EmailWithAttachments.msg"), System.IO.FileMode.Open, System.IO.FileAccess.Read)) { SampleOperationWithDotNetsStreamReaders(inputStream); GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); try { inputStream.Seek(0, System.IO.SeekOrigin.Begin); } catch (ObjectDisposedException) { Assert.Fail("The stream should not be disposed now"); } OperationWithMsgReader(inputStream); GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); try { inputStream.Seek(0, System.IO.SeekOrigin.Begin); } catch (ObjectDisposedException) { Assert.Fail("The stream should not be disposed now"); } } }
public static string ExtractUndeliverableEmailAddressFromMsg(Stream stream) { var message = new Storage.Message(stream); if (message.BodyText == null) { throw new VoteException("BodyText missing from message"); } var emails = ExtractAllEmailAddresses(message.BodyText); if (emails.Count == 0) { throw new VoteException("Message did not contain any qualifying email addresses"); } if (emails.Count > 1) { throw new VoteException("Message contains multiple email addresses"); } return(emails[0]); }
public string[] ExtractToFolder(string inputFile, string outputFolder, bool hyperlinks = false) { outputFolder = FileManager.CheckForBackSlash(outputFolder); _errorMessage = string.Empty; try { using (var stream = File.Open(inputFile, FileMode.Open, FileAccess.Read)) using (var message = new Storage.Message(stream)) { switch (message.Type) { case Storage.Message.MessageType.Email: return(WriteEmail(message, outputFolder, hyperlinks).ToArray()); case Storage.Message.MessageType.AppointmentRequest: case Storage.Message.MessageType.Appointment: case Storage.Message.MessageType.AppointmentResponse: return(WriteAppointment(message, outputFolder, hyperlinks).ToArray()); case Storage.Message.MessageType.Task: throw new Exception("An task file is not supported"); case Storage.Message.MessageType.StickyNote: return(WriteStickyNote(message, outputFolder, hyperlinks).ToArray()); case Storage.Message.MessageType.Unknown: throw new NotSupportedException("Unknown message type"); } } } catch (Exception e) { _errorMessage = GetInnerException(e); return(new string[0]); } // If we return here then the file was not supported return(new string[0]); }
public void SetFile(String file) { if (string.IsNullOrWhiteSpace(file)) { Logging.Error("No filename given."); return; } Logging.Log("File name: " + file); htmlPanel.Text = ""; if (file.ToLower().EndsWith(".msg")) { using (var msg = new Storage.Message(file)) { labelDate.Text = msg.SentOn.ToString(); labelFrom.Text = (msg.Sender != null ? msg.Sender.DisplayName + " <" + msg.Sender.Email + ">" : ""); labelTo.Text = msg.GetEmailRecipients(Storage.Recipient.RecipientType.To, false, false); //labelTo.Text += " | " + msg.GetEmailRecipients(Storage.Recipient.RecipientType.Cc, false, false); labelSubject.Text = msg.Subject; labelAttachments.Text = msg.Attachments.Count.ToString(); htmlPanel.Text = (string.IsNullOrWhiteSpace(msg.BodyHtml) ? msg.BodyText : msg.BodyHtml); } } if (file.ToLower().EndsWith(".eml")) { var msg = MimeMessage.Load(file); labelDate.Text = msg.Date.ToLocalTime().ToString(); labelFrom.Text = (msg.From != null ? msg.From.ToString() : ""); labelTo.Text = (msg.To != null ? msg.To.ToString() : ""); //labelTo.Text += " | " + msg.Cc.ToString(); labelSubject.Text = msg.Subject; labelAttachments.Text = msg.Attachments.Count().ToString(); htmlPanel.Text = (string.IsNullOrWhiteSpace(msg.HtmlBody) ? (string.IsNullOrWhiteSpace(msg.TextBody) ? "" : msg.TextBody) : msg.HtmlBody); } }
public void RemoveAttachments() { using (var inputStream = File.OpenRead(Path.Combine("SampleFiles", "EmailWith2Attachments.msg"))) using (var inputMessage = new Storage.Message(inputStream, FileAccess.ReadWrite)) { var attachments = inputMessage.Attachments.ToList(); foreach (var attachment in attachments) { inputMessage.DeleteAttachment(attachment); } using (var outputStream = new MemoryStream()) { inputMessage.Save(outputStream); using (var outputMessage = new Storage.Message(outputStream)) { var count = outputMessage.Attachments.Count; Assert.IsTrue(count == 0); } } } }
/// <summary> /// Change the E-mail sender addresses to a human readable format /// </summary> /// <param name="message">The Storage.Message object</param> /// <param name="convertToHref">When true then E-mail addresses are converted to hyperlinks</param> /// <param name="html">Set this to true when the E-mail body format is html</param> /// <returns></returns> private static string GetEmailSender(Storage.Message message, bool convertToHref, bool html) { var output = string.Empty; if (message == null) { return(string.Empty); } var tempEmailAddress = message.Sender.Email; var tempDisplayName = message.Sender.DisplayName; if (string.IsNullOrEmpty(tempEmailAddress) && message.Headers != null && message.Headers.From != null) { tempEmailAddress = RemoveSingleQuotes(message.Headers.From.Address); } if (string.IsNullOrEmpty(tempDisplayName) && message.Headers != null && message.Headers.From != null) { tempDisplayName = message.Headers.From.DisplayName; } var emailAddress = tempEmailAddress; var displayName = tempDisplayName; // Sometimes the E-mail address and displayname get swapped so check if they are valid if (!IsEmailAddressValid(tempEmailAddress) && IsEmailAddressValid(tempDisplayName)) { // Swap them emailAddress = tempDisplayName; displayName = tempEmailAddress; } else if (IsEmailAddressValid(tempDisplayName)) { // If the displayname is an emailAddress them move it emailAddress = tempDisplayName; displayName = tempDisplayName; } if (html) { emailAddress = HttpUtility.HtmlEncode(emailAddress); displayName = HttpUtility.HtmlEncode(displayName); } if (convertToHref && html && !string.IsNullOrEmpty(emailAddress)) { output += "<a href=\"mailto:" + emailAddress + "\">" + (!string.IsNullOrEmpty(displayName) ? displayName : emailAddress) + "</a>"; } else { if (!string.IsNullOrEmpty(emailAddress)) { output = emailAddress; } if (!string.IsNullOrEmpty(displayName)) { output += (!string.IsNullOrEmpty(emailAddress) ? " <" : string.Empty) + displayName + (!string.IsNullOrEmpty(emailAddress) ? ">" : string.Empty); } } return(output); }
static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Expected 2 command line arguments!"); Console.WriteLine("For example: EmailExtractor.exe \"c:\\<folder to read>\" \"c:\\filetowriteto.txt\""); return; } var folderIn = args[0]; if (!Directory.Exists(folderIn)) { Console.WriteLine("The directory '" + folderIn + "' does not exist"); return;; } var toFile = args[1]; // Get all the .msg files from the folder var files = new DirectoryInfo(folderIn).GetFiles("*.msg"); Console.WriteLine("Found '" + files.Count() + "' files to process"); // Loop through all the files foreach (var file in files) { Console.WriteLine("Checking file '" + file.FullName + "'"); // Load the msg file using (var message = new Storage.Message(file.FullName)) { Console.WriteLine("Found '" + message.Attachments.Count + "' attachments"); // Loop through all the attachments foreach (var attachment in message.Attachments) { // Try to cast the attachment to a Message file var msg = attachment as Storage.Message; // If the file not is null then we have an msg file if (msg != null) { using (msg) { Console.WriteLine("Found msg file '" + msg.Subject + "'"); if (!string.IsNullOrWhiteSpace(msg.MailingListSubscribe)) { Console.WriteLine("Mailing list subscribe page: '" + msg.MailingListSubscribe + "'"); } foreach (var recipient in msg.Recipients) { if (!string.IsNullOrWhiteSpace(recipient.Email)) { Console.WriteLine("Recipient E-mail: '" + recipient.Email + "'"); File.AppendAllText(toFile, recipient.Email + Environment.NewLine); } else if (!string.IsNullOrWhiteSpace(recipient.DisplayName)) { Console.WriteLine("Recipient display name: '" + recipient.DisplayName + "'"); File.AppendAllText(toFile, recipient.DisplayName + Environment.NewLine); } } } } } } } }
private static HashSet <int> GetNumbersFromEmail(string[] fileNames) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); HashSet <int> numbers = new HashSet <int>(); List <string[]> tableRows = new List <string[]>(); foreach (var fileName in fileNames) { using Storage.Message message = new Storage.Message(fileName); var htmlBody = message.BodyHtml; var numbersFromFile = new List <int>(); var lines = Utilities.RemoveAfterPhoneNumber(Utilities.StripHTML(Utilities.ReplaceHtmlNewlines(htmlBody))).Split("\n"); foreach (var line in lines) { if (numbersFromFile.Count >= 4) { break; } var numberListStart = Regex.Match(line, @"\d+, ").Value; if (string.IsNullOrEmpty(numberListStart)) { continue; } if (line.Split(',').Length < 4) { continue; } var splitLine = line.Split(',', '.'); foreach (var number in splitLine) { var numberCleaned = Regex.Match(number, @"\d+").Value; if (int.TryParse(numberCleaned, out int numberParsed) && numberParsed > 0 && numberParsed <= 90) { numbersFromFile.Add(numberParsed); } } } tableRows.Add(new[] { $"{message.FileName}", $"{message.SentOn.Value:d}", $"{string.Join(", ", numbersFromFile)}" }); numbers.UnionWith(numbersFromFile); } var tableRowsOrdered = tableRows.OrderBy(column => column[1]); var table = new Table(); table.AddColumns(new[] { "File Name", "Date", "Numbers" }); foreach (var tableRow in tableRowsOrdered) { table.AddRow(tableRow); } AnsiConsole.Render(new Panel(table).Header("Number extraction result")); return(numbers); }
public override string Parse() { StringBuilder result = new StringBuilder(); using (var stream = File.OpenRead(this.Context.Path)) using (var reader = new Storage.Message(stream)) { if (reader.Sender != null) { result.AppendFormat("[From] {0}{1}", string.IsNullOrEmpty(reader.Sender.DisplayName) ? reader.Sender.Email : string.Format("{0}<{1}>", reader.Sender.DisplayName, reader.Sender.Email), Environment.NewLine); } if (reader.Recipients.Count > 0) { StringBuilder recipientTo = new StringBuilder(); StringBuilder recipientCc = new StringBuilder(); StringBuilder recipientBcc = new StringBuilder(); foreach (var recipient in reader.Recipients) { string sRecipient = null; if (string.IsNullOrEmpty(recipient.DisplayName)) { sRecipient = recipient.Email + ";"; } else { sRecipient = string.Format("{0}<{1}>;", recipient.DisplayName, recipient.Email); } if (recipient.Type == MsgReader.Outlook.Storage.Recipient.RecipientType.To) { recipientTo.Append(sRecipient); } else if (recipient.Type == MsgReader.Outlook.Storage.Recipient.RecipientType.Cc) { recipientCc.Append(sRecipient); } else if (recipient.Type == MsgReader.Outlook.Storage.Recipient.RecipientType.Bcc) { recipientBcc.Append(sRecipient); } } if (recipientTo.Length > 0) { result.Append("[To] "); result.AppendLine(recipientTo.ToString()); } if (recipientCc.Length > 0) { result.Append("[Cc] "); result.AppendLine(recipientCc.ToString()); } if (recipientBcc.Length > 0) { result.Append("[Bcc] "); result.AppendLine(recipientBcc.ToString()); } } if (!string.IsNullOrEmpty(reader.Subject)) { result.AppendFormat("[Subject] {0}{1}", reader.Subject, Environment.NewLine); } result.AppendLine(); result.AppendLine(reader.BodyText); } return(result.ToString()); }
/// <summary> /// Maps all the filled <see cref="Storage.Task"/> properties to the corresponding extended file attributes /// </summary> /// <param name="message">The <see cref="Storage.Message"/> object</param> /// <param name="propertyWriter">The <see cref="ShellPropertyWriter"/> object</param> private void MapContactPropertiesToExtendedFileAttributes(Storage.Message message, ShellPropertyWriter propertyWriter) { // From propertyWriter.WriteProperty(SystemProperties.System.Message.FromAddress, message.Sender.Email); propertyWriter.WriteProperty(SystemProperties.System.Message.FromName, message.Sender.DisplayName); // Sent on propertyWriter.WriteProperty(SystemProperties.System.Message.DateSent, message.SentOn); // Full name propertyWriter.WriteProperty(SystemProperties.System.Contact.FullName, message.Contact.DisplayName); // Last name propertyWriter.WriteProperty(SystemProperties.System.Contact.LastName, message.Contact.SurName); // First name propertyWriter.WriteProperty(SystemProperties.System.Contact.FirstName, message.Contact.GivenName); // Job title propertyWriter.WriteProperty(SystemProperties.System.Contact.JobTitle, message.Contact.Function); // Department propertyWriter.WriteProperty(SystemProperties.System.Contact.Department, message.Contact.Department); // Company propertyWriter.WriteProperty(SystemProperties.System.Company, message.Contact.Company); // Business address propertyWriter.WriteProperty(SystemProperties.System.Contact.BusinessAddress, message.Contact.WorkAddress); // Home address propertyWriter.WriteProperty(SystemProperties.System.Contact.HomeAddress, message.Contact.HomeAddress); // Other address propertyWriter.WriteProperty(SystemProperties.System.Contact.OtherAddress, message.Contact.OtherAddress); // Instant messaging propertyWriter.WriteProperty(SystemProperties.System.Contact.IMAddress, message.Contact.InstantMessagingAddress); // Business telephone number propertyWriter.WriteProperty(SystemProperties.System.Contact.BusinessTelephone, message.Contact.BusinessTelephoneNumber); // Assistant's telephone number propertyWriter.WriteProperty(SystemProperties.System.Contact.AssistantTelephone, message.Contact.AssistantTelephoneNumber); // Company main phone propertyWriter.WriteProperty(SystemProperties.System.Contact.CompanyMainTelephone, message.Contact.CompanyMainTelephoneNumber); // Home telephone number propertyWriter.WriteProperty(SystemProperties.System.Contact.HomeTelephone, message.Contact.HomeTelephoneNumber); // Mobile phone propertyWriter.WriteProperty(SystemProperties.System.Contact.MobileTelephone, message.Contact.CellularTelephoneNumber); // Car phone propertyWriter.WriteProperty(SystemProperties.System.Contact.CarTelephone, message.Contact.CarTelephoneNumber); // Callback propertyWriter.WriteProperty(SystemProperties.System.Contact.CallbackTelephone, message.Contact.CallbackTelephoneNumber); // Primary telephone number propertyWriter.WriteProperty(SystemProperties.System.Contact.PrimaryTelephone, message.Contact.PrimaryTelephoneNumber); // Telex propertyWriter.WriteProperty(SystemProperties.System.Contact.TelexNumber, message.Contact.TelexNumber); // TTY/TDD phone propertyWriter.WriteProperty(SystemProperties.System.Contact.TTYTDDTelephone, message.Contact.TextTelephone); // Business fax propertyWriter.WriteProperty(SystemProperties.System.Contact.BusinessFaxNumber, message.Contact.BusinessFaxNumber); // Home fax propertyWriter.WriteProperty(SystemProperties.System.Contact.HomeFaxNumber, message.Contact.HomeFaxNumber); // E-mail propertyWriter.WriteProperty(SystemProperties.System.Contact.EmailAddress, message.Contact.Email1EmailAddress); propertyWriter.WriteProperty(SystemProperties.System.Contact.EmailName, message.Contact.Email1DisplayName); // E-mail 2 propertyWriter.WriteProperty(SystemProperties.System.Contact.EmailAddress2, message.Contact.Email2EmailAddress); // E-mail 3 propertyWriter.WriteProperty(SystemProperties.System.Contact.EmailAddress3, message.Contact.Email3EmailAddress); // Birthday propertyWriter.WriteProperty(SystemProperties.System.Contact.Birthday, message.Contact.Birthday); // Anniversary propertyWriter.WriteProperty(SystemProperties.System.Contact.Anniversary, message.Contact.WeddingAnniversary); // Spouse/Partner propertyWriter.WriteProperty(SystemProperties.System.Contact.SpouseName, message.Contact.SpouseName); // Profession propertyWriter.WriteProperty(SystemProperties.System.Contact.Profession, message.Contact.Profession); // Assistant propertyWriter.WriteProperty(SystemProperties.System.Contact.AssistantName, message.Contact.AssistantName); // Web page propertyWriter.WriteProperty(SystemProperties.System.Contact.Webpage, message.Contact.Html); // Categories var categories = message.Categories; if (categories != null) { propertyWriter.WriteProperty(SystemProperties.System.Category, String.Join("; ", String.Join("; ", categories))); } }
/// <summary> /// Maps all the filled <see cref="Storage.Appointment"/> properties to the corresponding extended file attributes /// </summary> /// <param name="message">The <see cref="Storage.Message"/> object</param> /// <param name="propertyWriter">The <see cref="ShellPropertyWriter"/> object</param> private void MapAppointmentPropertiesToExtendedFileAttributes(Storage.Message message, ShellPropertyWriter propertyWriter) { // From propertyWriter.WriteProperty(SystemProperties.System.Message.FromAddress, message.Sender.Email); propertyWriter.WriteProperty(SystemProperties.System.Message.FromName, message.Sender.DisplayName); // Sent on if (message.SentOn != null) { propertyWriter.WriteProperty(SystemProperties.System.Message.DateSent, message.SentOn); } // Subject propertyWriter.WriteProperty(SystemProperties.System.Subject, message.Subject); // Location propertyWriter.WriteProperty(SystemProperties.System.Calendar.Location, message.Appointment.Location); // Start propertyWriter.WriteProperty(SystemProperties.System.StartDate, message.Appointment.Start); // End propertyWriter.WriteProperty(SystemProperties.System.StartDate, message.Appointment.End); // Recurrence type propertyWriter.WriteProperty(SystemProperties.System.Calendar.IsRecurring, message.Appointment.RecurrenceType != AppointmentRecurrenceType.None); // Status propertyWriter.WriteProperty(SystemProperties.System.Status, message.Appointment.ClientIntentText); // Appointment organizer (FROM) propertyWriter.WriteProperty(SystemProperties.System.Calendar.OrganizerAddress, message.Sender.Email); propertyWriter.WriteProperty(SystemProperties.System.Calendar.OrganizerName, message.Sender.DisplayName); // Mandatory participants (TO) propertyWriter.WriteProperty(SystemProperties.System.Calendar.RequiredAttendeeNames, message.Appointment.ToAttendees); // Optional participants (CC) propertyWriter.WriteProperty(SystemProperties.System.Calendar.OptionalAttendeeNames, message.Appointment.CcAttendees); // Categories var categories = message.Categories; if (categories != null) { propertyWriter.WriteProperty(SystemProperties.System.Category, String.Join("; ", String.Join("; ", categories))); } // Urgent propertyWriter.WriteProperty(SystemProperties.System.Importance, message.Importance); propertyWriter.WriteProperty(SystemProperties.System.ImportanceText, message.ImportanceText); // Attachments var attachments = message.GetAttachmentNames(); if (string.IsNullOrEmpty(attachments)) { propertyWriter.WriteProperty(SystemProperties.System.Message.HasAttachments, false); propertyWriter.WriteProperty(SystemProperties.System.Message.AttachmentNames, null); } else { propertyWriter.WriteProperty(SystemProperties.System.Message.HasAttachments, true); propertyWriter.WriteProperty(SystemProperties.System.Message.AttachmentNames, attachments); } }
/// <summary> /// Maps all the filled <see cref="Storage.Message"/> properties to the corresponding extended file attributes /// </summary> /// <param name="message">The <see cref="Storage.Message"/> object</param> /// <param name="propertyWriter">The <see cref="ShellPropertyWriter"/> object</param> private void MapEmailPropertiesToExtendedFileAttributes(Storage.Message message, ShellPropertyWriter propertyWriter) { // From propertyWriter.WriteProperty(SystemProperties.System.Message.FromAddress, message.Sender.Email); propertyWriter.WriteProperty(SystemProperties.System.Message.FromName, message.Sender.DisplayName); // Sent on propertyWriter.WriteProperty(SystemProperties.System.Message.DateSent, message.SentOn); // To propertyWriter.WriteProperty(SystemProperties.System.Message.ToAddress, message.GetEmailRecipients(RecipientType.To, false, false)); // CC propertyWriter.WriteProperty(SystemProperties.System.Message.CcAddress, message.GetEmailRecipients(RecipientType.Cc, false, false)); // BCC propertyWriter.WriteProperty(SystemProperties.System.Message.BccAddress, message.GetEmailRecipients(RecipientType.Bcc, false, false)); // Subject propertyWriter.WriteProperty(SystemProperties.System.Subject, message.Subject); // Urgent propertyWriter.WriteProperty(SystemProperties.System.Importance, message.Importance); propertyWriter.WriteProperty(SystemProperties.System.ImportanceText, message.ImportanceText); // Attachments var attachments = message.GetAttachmentNames(); if (string.IsNullOrEmpty(attachments)) { propertyWriter.WriteProperty(SystemProperties.System.Message.HasAttachments, false); propertyWriter.WriteProperty(SystemProperties.System.Message.AttachmentNames, null); } else { propertyWriter.WriteProperty(SystemProperties.System.Message.HasAttachments, true); propertyWriter.WriteProperty(SystemProperties.System.Message.AttachmentNames, attachments); } // Clear properties propertyWriter.WriteProperty(SystemProperties.System.StartDate, null); propertyWriter.WriteProperty(SystemProperties.System.DueDate, null); propertyWriter.WriteProperty(SystemProperties.System.DateCompleted, null); propertyWriter.WriteProperty(SystemProperties.System.IsFlaggedComplete, null); propertyWriter.WriteProperty(SystemProperties.System.FlagStatusText, null); // Follow up if (message.Flag != null) { propertyWriter.WriteProperty(SystemProperties.System.IsFlagged, true); propertyWriter.WriteProperty(SystemProperties.System.FlagStatusText, message.Flag.Request); // Flag status text propertyWriter.WriteProperty(SystemProperties.System.FlagStatusText, message.Task.StatusText); // When complete if (message.Task.Complete != null && (bool)message.Task.Complete) { // Flagged complete propertyWriter.WriteProperty(SystemProperties.System.IsFlaggedComplete, true); // Task completed date if (message.Task.CompleteTime != null) { propertyWriter.WriteProperty(SystemProperties.System.DateCompleted, (DateTime)message.Task.CompleteTime); } } else { // Flagged not complete propertyWriter.WriteProperty(SystemProperties.System.IsFlaggedComplete, false); propertyWriter.WriteProperty(SystemProperties.System.DateCompleted, null); // Task startdate if (message.Task.StartDate != null) { propertyWriter.WriteProperty(SystemProperties.System.StartDate, (DateTime)message.Task.StartDate); } // Task duedate if (message.Task.DueDate != null) { propertyWriter.WriteProperty(SystemProperties.System.DueDate, (DateTime)message.Task.DueDate); } } } // Categories var categories = message.Categories; if (categories != null) { propertyWriter.WriteProperty(SystemProperties.System.Category, String.Join("; ", String.Join("; ", categories))); } }
private GenResult EmailMessageFromMessage( StoredContact sender, StoredContact recipient, Storage.Message msg) { GenResult res = new GenResult(); try { EmailAddress em = Contact.Bind(this.service, new ItemId(sender.UniqId)) .EmailAddresses[EmailAddressKey.EmailAddress1]; EmailMessage newMsg = new EmailMessage(this.service) { From = em, Sender = em, Body = new MessageBody(msg.BodyHtml), Subject = msg.Subject }; newMsg.Save(WellKnownFolderName.Drafts); foreach (object obj in msg.Attachments) { Storage.Attachment attach = obj as Storage.Attachment; if (attach == null) { continue; } newMsg.Attachments.AddFileAttachment(attach.FileName, attach.Data); } this.FillAdresses(ref newMsg, recipient.Email); res.msg = newMsg; // делаем ли форвард if (RndTrueFalse()) { newMsg.Update(ConflictResolutionMode.AlwaysOverwrite); ResponseMessage respMsg = newMsg.CreateForward(); respMsg.BodyPrefix = @"test body prefix for forward message"; this.FillAdressesForResponse(ref respMsg, this.RndRecipMail()); respMsg.Save(WellKnownFolderName.Drafts); res.response = respMsg; } // делаем ли реплай if (RndTrueFalse()) { /*newMsg.ReplyTo.Add(_RndRecipMail()); * if (_RndTrueFalse()) * { * newMsg.ReplyTo.Add(_RndRecipMail()); * } * * if (_RndTrueFalse()) */ { newMsg.Update(ConflictResolutionMode.AlwaysOverwrite); ResponseMessage replMsg = newMsg.CreateReply(RndTrueFalse()); replMsg.BodyPrefix = @"test body prefix for reply message"; this.FillAdressesForResponse(ref replMsg, recipient.Email); replMsg.Save(WellKnownFolderName.Drafts); res.reply = replMsg; } } } catch (Exception exc) { GenericLogger <Generator> .Error( LocalizibleStrings.ErrorCreateFromTemplate + msg.FileName, exc); } return(res); }
/// <summary> /// Change the E-mail sender addresses to a human readable format /// </summary> /// <param name="message">The Storage.Message object</param> /// <param name="convertToHref">When true the E-mail addresses are converted to hyperlinks</param> /// <param name="type">This types says if we want to get the TO's or CC's</param> /// <param name="html">Set this to true when the E-mail body format is html</param> /// <returns></returns> private static string GetEmailRecipients(Storage.Message message, Storage.Recipient.RecipientType type, bool convertToHref, bool html) { var output = string.Empty; var recipients = new List <Recipient>(); if (message == null) { return(output); } foreach (var recipient in message.Recipients) { // First we filter for the correct recipient type if (recipient.Type == type) { recipients.Add(new Recipient { EmailAddress = recipient.Email, DisplayName = recipient.DisplayName }); } } if (recipients.Count == 0 && message.Headers != null) { switch (type) { case Storage.Recipient.RecipientType.To: if (message.Headers.To != null) { recipients.AddRange(message.Headers.To.Select(to => new Recipient { EmailAddress = to.Address, DisplayName = to.DisplayName })); } break; case Storage.Recipient.RecipientType.Cc: if (message.Headers.Cc != null) { recipients.AddRange(message.Headers.Cc.Select(cc => new Recipient { EmailAddress = cc.Address, DisplayName = cc.DisplayName })); } break; case Storage.Recipient.RecipientType.Bcc: if (message.Headers.Bcc != null) { recipients.AddRange(message.Headers.Bcc.Select(bcc => new Recipient { EmailAddress = bcc.Address, DisplayName = bcc.DisplayName })); } break; } } foreach (var recipient in recipients) { if (output != string.Empty) { output += "; "; } var tempEmailAddress = RemoveSingleQuotes(recipient.EmailAddress); var tempDisplayName = RemoveSingleQuotes(recipient.DisplayName); var emailAddress = tempEmailAddress; var displayName = tempDisplayName; // Sometimes the E-mail address and displayname get swapped so check if they are valid if (!IsEmailAddressValid(tempEmailAddress) && IsEmailAddressValid(tempDisplayName)) { // Swap them emailAddress = tempDisplayName; displayName = tempEmailAddress; } else if (IsEmailAddressValid(tempDisplayName)) { // If the displayname is an emailAddress them move it emailAddress = tempDisplayName; displayName = tempDisplayName; } if (html) { emailAddress = HttpUtility.HtmlEncode(emailAddress); displayName = HttpUtility.HtmlEncode(displayName); } if (convertToHref && html && !string.IsNullOrEmpty(emailAddress)) { output += "<a href=\"mailto:" + emailAddress + "\">" + (!string.IsNullOrEmpty(displayName) ? displayName : emailAddress) + "</a>"; } else { if (!string.IsNullOrEmpty(emailAddress)) { output = emailAddress; } if (!string.IsNullOrEmpty(displayName)) { output += (!string.IsNullOrEmpty(emailAddress) ? " <" : string.Empty) + displayName + (!string.IsNullOrEmpty(emailAddress) ? ">" : string.Empty); } } } return(output); }