static void Main(string[] args) { try { // Registering encoding provider for .net core solution System.Text.EncodingProvider encodingProvider = System.Text.CodePagesEncodingProvider.Instance; Encoding.RegisterProvider(encodingProvider); // Parse MessageContents using MsgReader Library // MsgReader library can be obtained from: https://github.com/Sicos1977/MSGReader using (var msg = new MsgReader.Outlook.Storage.Message("HtmlSampleEmailWithAttachment.msg")) { // Get Sender information var from = msg.GetEmailSender(false, false); // Message sent datetime var sentOn = msg.SentOn; // Recipient To information var recipientsTo = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, false, false); // Recipient CC information var recipientsCc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, false, false); // Message subject var subject = msg.Subject; // Get Message Body var msgBody = msg.BodyHtml; // Prepare PDF docuemnt using (Document outputDocument = new Document()) { // Add registration keys outputDocument.RegistrationName = "demo"; outputDocument.RegistrationKey = "demo"; // Add page Page page = new Page(PaperFormat.A4); outputDocument.Pages.Add(page); // Add sample content Font font = new Font(StandardFonts.Times, 12); Brush brush = new SolidBrush(); // Add Email contents int topMargin = 20; page.Canvas.DrawString($"File Name: {msg.FileName}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"From: {from}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"Sent On: {(sentOn.HasValue ? sentOn.Value.ToString("MM/dd/yyyy HH:mm") : "")}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"To: {recipientsTo}", font, brush, 20, (topMargin += 20)); if (!string.IsNullOrEmpty(recipientsCc)) { page.Canvas.DrawString($"CC: {recipientsCc}", font, brush, 20, (topMargin += 20)); } page.Canvas.DrawString($"Subject: {subject}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString("Message body and attachments in next page.", font, brush, 20, (topMargin += 20)); // Convert Html body to PDF in order to retain all formatting. using (HtmlToPdfConverter converter = new HtmlToPdfConverter()) { converter.PageSize = PaperKind.A4; converter.Orientation = Bytescout.PDF.Converters.PaperOrientation.Portrait; // Convert input HTML to stream byte[] byteArrayBody = Encoding.UTF8.GetBytes(msgBody); MemoryStream inputStream = new MemoryStream(byteArrayBody); // Create output stream to store generated PDF file MemoryStream outputStream = new MemoryStream(); // Convert HTML to PDF converter.ConvertHtmlToPdf(inputStream, outputStream); // Create new document from generated output stream Document docContent = new Document(outputStream); // Append all pages to main PDF foreach (Page item in docContent.Pages) { outputDocument.Pages.Add(item); } // Get attachments from message (if any, and append to document) if (msg.Attachments.Count > 0) { foreach (MsgReader.Outlook.Storage.Attachment itmAttachment in msg.Attachments) { // Get Memory Stream MemoryStream attachmentMemoryStream = new MemoryStream(itmAttachment.Data); // Append Attachment Document docAttachment = new Document(attachmentMemoryStream); // Append all pages to main PDF foreach (Page item in docAttachment.Pages) { outputDocument.Pages.Add(item); } } } // Save output file outputDocument.Save("result.pdf"); } // Open result document in default associated application (for demo purpose) ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf"); processStartInfo.UseShellExecute = true; Process.Start(processStartInfo); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); } }
public static string GetEmailCcEx(this MsgReader.Outlook.Storage.Message msg) { return(msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, true, false).EmptyIfNullEx()); }
public static void Main() { try { String useInPath = ConfigurationManager.AppSettings["inpath"].ToString(); String useOutPath = ConfigurationManager.AppSettings["outpath"].ToString(); try { Directory.CreateDirectory(useOutPath); } catch { Console.WriteLine("Directory " + useOutPath + " already exists."); } String slash = Convert.ToString(Convert.ToChar(92)); //store the slash so it can be used in the filename later #region Handle msg formatted file try { //Get all outlook message items in the folder, these mail messages are exported to the useInPath folder from the workflow action after the mailbox importer imports the message sent by nCino String[] allitems = Directory.GetFiles(useInPath, "*.msg"); foreach (String item in allitems) { FileInfo f = new FileInfo(item); String itemname = f.Name; //the name of the message file which is the dochandle that the workflow export for network folder gave it //write the text portion of the body out to a temporary file replacing tabs with new lines String temptxtfile = useInPath + slash + itemname + ".txt"; File.Delete(temptxtfile); //setup the filename for the one that will contain the COLD records, delete it if it already exists String useOUTfile = useOutPath + slash + "GIM_Repair_nCinoEmail_" + itemname + ".txt"; File.Delete(useOUTfile); try { using (var msg = new MsgReader.Outlook.Storage.Message(item)) { var textBody = msg.BodyText.Replace("\t", "\n").Replace("_R1", ""); File.WriteAllText(temptxtfile, textBody); } } catch { Console.WriteLine("File is not an Outlook formated message."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Environment.Exit(0); } //read in the file that contains the text version of the message body foreach (String lineintxt in File.ReadLines(temptxtfile)) { try { //identify any large integers as loan numbers Int64 lineinint = Convert.ToInt64(lineintxt); if (lineinint > 9999) { LOANnumber = Convert.ToString(lineinint); } } catch { //identify nCino AppIDs as anything that starts with AN- if (lineintxt.StartsWith("AN-")) { String ANnumber = lineintxt; if (Convert.ToInt64(LOANnumber) > 0) { String GIMDocType = "WF GIM Repair ".Substring(0, 20); //COLD config is doctype in 1st 20 characters String GIMMaintType = "nCinoLoan#Swap ".Substring(0, 25); //COLD config is desc kw in 21 for 25 characters String lineout = GIMDocType + GIMMaintType + "||" + ANnumber + "|" + LOANnumber + "\n"; File.AppendAllText(useOUTfile, lineout); } //some AN- may not be preceeded by a loan number so this ensures only records that have a Loan# and an AN- number are handled LOANnumber = "0"; } } } //delete the .msg item File.Delete(item); //delete the .txt file that stored the message body text File.Delete(temptxtfile); } } catch (Exception ex) { Console.WriteLine("Exception encountered .msg region:" + ex); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Environment.Exit(0); } #endregion #region Handle eml formatted file try { //Get all eml message items in the folder, these mail messages are exported to the useInPath folder from the workflow action after the mailbox importer imports the message sent by nCino String[] allitemseml = Directory.GetFiles(useInPath, "*.eml"); foreach (String item in allitemseml) { foundhtml = 0; FileInfo f = new FileInfo(item); String itemname = f.Name; //the name of the message file which is the dochandle that the workflow export for network folder gave it //write the text portion of the body out to a temporary file replacing tabs with new lines String temptxtfile = useInPath + slash + itemname + ".html"; File.Delete(temptxtfile); String temptxtfile2 = useInPath + slash + itemname + ".newhtmltxt"; File.Delete(temptxtfile2); //setup the filename for the one that will contain the COLD records, delete it if it already exists String useOUTfile = useOutPath + slash + "GIM_Repair_nCinoEmail_" + itemname + ".txt"; File.Delete(useOUTfile); #region CreateGoodHTML Console.WriteLine("Processing file: " + item + " step 1 of 3"); string[] badhtmllines = File.ReadAllLines(item); foreach (string badhtmlline in badhtmllines) { bool foundhtmlstart = badhtmlline.Contains("<html"); bool foundbodystart = badhtmlline.Contains("<body"); if (foundhtmlstart == true) { lineout = "<html>"; File.AppendAllText(temptxtfile, lineout); } else { if (foundbodystart == true) { foundhtml = 1; } if (foundhtml == 1) { lineout = badhtmlline; lineout = lineout.Replace("<br>", "").Replace(" ", "").Replace("_R1", ""); if (lineout.Length > 0 && lineout.Substring(lineout.Length - 1, 1) == "=") { lineout = lineout.Substring(0, lineout.Length - 1); } File.AppendAllText(temptxtfile, lineout.Replace("=3D", "=").Replace("<o:p>", "").Replace("</o:p>", "")); } } } #endregion #region CleanUpHTMLerrors //read temptxtfile as one line, do replaces as in lines 162 & 167 and any others that crop up and write out as tmptxtfile4 Console.WriteLine("Processing file: " + item + " step 2 of 3"); try { string[] goodhtmllines = File.ReadAllLines(temptxtfile); foreach (string goodhtmlline in goodhtmllines) { string goodhtmllineout = goodhtmlline.Replace("<", "\r<");//.Replace("=3D", "=").Replace("<o:p>", "").Replace("</o:p>", "").Replace("<br>", "").Replace(" ", "").Replace("_R1", "").Replace("_M1", ""); goodhtmllineout = goodhtmllineout.Replace("\r<html>", "<html>"); File.AppendAllText(temptxtfile2, goodhtmllineout); } } catch (Exception ex) { Console.WriteLine("Exception encountered CleanUpHTMLerrors region:" + ex); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Environment.Exit(1); } #endregion #region ReadLinesAsTableColumns Console.WriteLine("Processing file: " + item + " step 3 of 3"); string[] tdlinein = File.ReadAllLines(temptxtfile2); foreach (string tdline in tdlinein) { if (tdline.Length > 10) { if (tdline.Substring(0, 9) == "<tr class") { colcount = 0; lineout2 = ""; loannumber = ""; appid = ""; } } if (tdline.Length > 3) { if (tdline.Substring(0, 3) == "<td") { colcount++; } } if (colcount == 1 && tdline != "</td>") { loannumber = tdline.Substring(tdline.IndexOf(">") + 1, tdline.Length - tdline.IndexOf(">") - 1); if (loannumber.IndexOf("_") > 0) { loannumber = loannumber.Substring(0, loannumber.IndexOf("_") - 1); } } if (colcount == 3) { if (loannumber.Length >= 2) { appid = tdline.Substring(tdline.IndexOf(">") + 1, tdline.Length - tdline.IndexOf(">") - 1); if (loannumber != "-" && appid != "" && loannumber.Substring(0, 2) != "AN") { String GIMDocType = "WF GIM Repair ".Substring(0, 20); //COLD config is doctype in 1st 20 characters String GIMMaintType = "nCinoLoan#Swap ".Substring(0, 25); //COLD config is desc kw in 21 for 25 characters lineout2 = GIMDocType + GIMMaintType + "||" + appid + "|" + loannumber + "\n"; File.AppendAllText(useOUTfile, lineout2); } } } } Console.WriteLine("**********Finished processing file: " + item + "***********"); #endregion #region CleanUp //delete the .msg item File.Delete(item); //delete the .txt file that stored the message body has html File.Delete(temptxtfile); //delete the .txt file that stored the good html rows File.Delete(temptxtfile2); #endregion } } catch (Exception ex) { Console.WriteLine("Exception encountered .eml region:" + ex); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Environment.Exit(1); } #endregion } catch { Console.WriteLine("Config file does not exist or does not meet requirements."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Environment.Exit(1); } finally { Environment.Exit(0); } }
static void Main(string[] args) { try { // Parse MessageContents using MsgReader Library // MsgReader library can be obtained from: https://github.com/Sicos1977/MSGReader using (var msg = new MsgReader.Outlook.Storage.Message("EmailWithAttachments.msg")) { // Get Sender information var from = msg.GetEmailSender(false, false); // Message sent datetime var sentOn = msg.SentOn; // Recipient To information var recipientsTo = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, false, false); // Recipient CC information var recipientsCc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, false, false); // Recipient BCC information var recipientBcc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Bcc, false, false); // Message subject var subject = msg.Subject; // Get Message Body var msgBody = msg.BodyHtml; // Prepare PDF docuemnt using (Document outputDocument = new Document()) { // Add registration keys outputDocument.RegistrationName = "demo"; outputDocument.RegistrationKey = "demo"; // Add page Page page = new Page(PaperFormat.A4); outputDocument.Pages.Add(page); // Add sample content Font font = new Font(StandardFonts.Times, 12); Brush brush = new SolidBrush(); // Add Email contents int topMargin = 20; page.Canvas.DrawString($"File Name: {msg.FileName}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"From: {from}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"Sent On: {(sentOn.HasValue ? sentOn.Value.ToString("MM/dd/yyyy HH:mm") : "")}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"To: {recipientsTo}", font, brush, 20, (topMargin += 20)); if (!string.IsNullOrEmpty(recipientsCc)) { page.Canvas.DrawString($"CC: {recipientsCc}", font, brush, 20, (topMargin += 20)); } if (!string.IsNullOrEmpty(recipientBcc)) { page.Canvas.DrawString($"BCC: {recipientBcc}", font, brush, 20, (topMargin += 20)); } page.Canvas.DrawString($"Subject: {subject}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString("Message body in next page.", font, brush, 20, (topMargin += 20)); // Convert Html body to PDF in order to retain all formatting. using (HtmlToPdfConverter converter = new HtmlToPdfConverter()) { converter.PageSize = PaperKind.A4; converter.Orientation = Bytescout.PDF.Converters.PaperOrientation.Portrait; // Get all inline attachment, and replace them foreach (MsgReader.Outlook.Storage.Attachment itmAttachment in msg.Attachments) { if (itmAttachment.IsInline) { var oData = itmAttachment.Data; var dataBase64 = Convert.ToBase64String(oData); // Replace within email msgBody = msgBody.Replace($"src=\"{itmAttachment.FileName}\"", $"src=\"{ "data:image/jpeg;base64," + dataBase64}\""); } } // Convert input HTML to stream byte[] byteArrayBody = Encoding.UTF8.GetBytes(msgBody); MemoryStream inputStream = new MemoryStream(byteArrayBody); // Create output stream to store generated PDF file using (var outputStream = new MemoryStream()) { // Convert HTML to PDF converter.ConvertHtmlToPdf(inputStream, outputStream); // Create new document from generated output stream Document docContent = new Document(outputStream); // Append all pages to main PDF foreach (Page item in docContent.Pages) { outputDocument.Pages.Add(item); } // Apped all other attachments foreach (MsgReader.Outlook.Storage.Attachment itmAttachment in msg.Attachments) { if (!itmAttachment.IsInline) { // Attachment is image, so adding accordingly var pageAttachment = new Page(PaperFormat.A4); Canvas canvas = pageAttachment.Canvas; var oAttachmentStream = new MemoryStream(itmAttachment.Data); Image imageAttachment = new Image(oAttachmentStream); canvas.DrawImage(imageAttachment, 20, 20); // Add attachment outputDocument.Pages.Add(pageAttachment); } } // Save output file outputDocument.Save("result.pdf"); } } // Open result document in default associated application (for demo purpose) ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf"); processStartInfo.UseShellExecute = true; Process.Start(processStartInfo); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); } }
public static string GetReceivedOnEx(this MsgReader.Outlook.Storage.Message msg) { DateTime date = msg.GetDReceivedOnEx(); return(DateTools.DateToString(date, DateTools.Resolution.MINUTE)); }
public string Read(string file) { Preconditions.CheckArgument(file); Preconditions.CheckArgument(htmlMessageTemplate); FileInfo inFile = new FileInfo(file); if (!inFile.Exists) { throw new FileNotFoundException("Input Excel file not found.", file); } string ext = Path.GetExtension(inFile.FullName); if (ext.ToLower().CompareTo(".msg") == 0) { MsgReader.Outlook.Storage.Message message = new MsgReader.Outlook.Storage.Message(file); MatchCollection matches = Regex.Matches(htmlMessageTemplate, FIELD_REGEX); if (matches != null && matches.Count > 0) { string html = new string(htmlMessageTemplate.ToCharArray()); string htmlBody = null; foreach (Match match in matches) { string k = match.Groups[1].Value; string v = match.Groups[2].Value; string t = null; if (v.CompareTo(FIELD_BCC) == 0) { t = message.GetEmailRecipients(MsgReader.Outlook.RecipientType.Bcc, true, true); } else if (v.CompareTo(FIELD_CC) == 0) { t = message.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, true, true); } else if (v.CompareTo(FIELD_TO) == 0) { t = message.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, true, true); } else if (v.CompareTo(FIELD_FROM) == 0) { t = message.GetEmailSender(true, true); } else if (v.CompareTo(FIELD_RECEIVED) == 0) { DateTime dt = (DateTime)message.ReceivedOn; t = dt.ToString(dateFormat); } else if (v.CompareTo(FIELD_SENT) == 0) { DateTime dt = (DateTime)message.SentOn; t = dt.ToString(dateFormat); } else if (v.CompareTo(FIELD_SUBJECT) == 0) { t = message.Subject; } else if (v.CompareTo(FIELD_BODY) == 0) { if (message.BodyHtml != null) { htmlBody = message.BodyHtml; continue; } else { t = message.BodyText; } } if (!String.IsNullOrEmpty(t)) { t = String.Format("{0}{1}", k, t); html = ReplaceMatch(html, match, t); } } return(PostProcess(html, htmlBody)); } } else { MsgReader.Mime.Message message = MsgReader.Mime.Message.Load(inFile); MatchCollection matches = Regex.Matches(htmlMessageTemplate, FIELD_REGEX); if (matches != null && matches.Count > 0) { string html = new string(htmlMessageTemplate.ToCharArray()); string htmlBody = null; foreach (Match match in matches) { string k = match.Groups[1].Value; string v = match.Groups[2].Value; string t = null; if (v.CompareTo(FIELD_BCC) == 0) { t = GetRecepientsString(message.Headers.Bcc); } else if (v.CompareTo(FIELD_CC) == 0) { t = GetRecepientsString(message.Headers.Cc); } else if (v.CompareTo(FIELD_TO) == 0) { t = GetRecepientsString(message.Headers.To); } else if (v.CompareTo(FIELD_FROM) == 0) { t = EmailAddressString(message.Headers.From); } else if (v.CompareTo(FIELD_RECEIVED) == 0) { // TODO: Need to fix this. DateTime dt = DateTime.Now; t = dt.ToString(dateFormat); } else if (v.CompareTo(FIELD_SENT) == 0) { DateTime dt = (DateTime)message.Headers.DateSent; t = dt.ToString(dateFormat); } else if (v.CompareTo(FIELD_SUBJECT) == 0) { t = message.Headers.Subject; } else if (v.CompareTo(FIELD_BODY) == 0) { if (message.HtmlBody != null) { htmlBody = message.HtmlBody.GetBodyAsText(); continue; } else { t = message.TextBody.GetBodyAsText(); } } if (!String.IsNullOrEmpty(t)) { t = String.Format("{0}{1}", k, t); html = ReplaceMatch(html, match, t); } } return(PostProcess(html, htmlBody)); } } return(null); }
private void button1_Click(object sender, RibbonControlEventArgs e) { var m = e.Control.Context as Inspector; var mailitem = m.CurrentItem as MailItem; if (mailitem != null) { if (mailitem.Attachments.Count > 0) { try { string socServer = Settings1.Default.server; var cred = CredentialManager.ReadCredential("PhishPhinder Outlook"); string socUser = cred.UserName; string socPass = cred.Password; //Configure session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = socServer, PortNumber = 990, UserName = socUser, Password = socPass, FtpSecure = FtpSecure.Implicit, }; using (Session session = new Session()) { try { // Connect session.Open(sessionOptions); // Upload files foreach (Microsoft.Office.Interop.Outlook.Attachment item in mailitem.Attachments) { item.SaveAsFile(Path.Combine(@"c:\temp", item.FileName)); var uploadFile = (Path.Combine(@"c:\temp", item.FileName)); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; session.PutFiles(uploadFile, "/", false, transferOptions); using (var msg = new MsgReader.Outlook.Storage.Message(Path.Combine(@"c:\temp", item.FileName))) { var from = msg.Sender; var sentOn = msg.SentOn; string subject = msg.Subject; Microsoft.Office.Interop.Outlook.Application cApp = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook.MailItem SOCemail = cApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); SOCemail.Subject = "Phish reported to SOC"; SOCemail.Body = $"The following message has been uploaded to the SOC FTPS server for review:\n\nSubject: \"{subject}\"\nSent On: \"{sentOn}\"".Replace("\n", Environment.NewLine); SOCemail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh; Microsoft.Office.Interop.Outlook.AddressEntry cUser = cApp.Session.CurrentUser.AddressEntry; Microsoft.Office.Interop.Outlook.ExchangeUser cmanager = cUser.GetExchangeUser().GetExchangeUserManager(); SOCemail.Recipients.Add("*****@*****.**"); SOCemail.Recipients.Add("*****@*****.**"); SOCemail.Recipients.ResolveAll(); SOCemail.Send(); } File.Delete(Path.Combine(@"c:\temp", item.FileName)); } MessageBox.Show("This phish has been reported to the SOC"); session.Close(); } //Catch connection failures catch (System.Exception ex) { MessageBox.Show("Connection failed. Please check your username and password."); } } } catch (System.NullReferenceException ex1) { MessageBox.Show("Please populate your settings before continuing."); } } else { //Thrown if there are no attachments MessageBox.Show("This ain't no phish!"); } } }
static void Main(string[] args) { try { Console.WriteLine("Please wait while PDF is being created..."); // Parse MessageContents using MsgReader Library // MsgReader library can be obtained from: https://github.com/Sicos1977/MSGReader using (var msg = new MsgReader.Outlook.Storage.Message("TxtSampleEmail.msg")) { // Get Sender information var from = msg.GetEmailSender(false, false); // Message sent datetime var sentOn = msg.SentOn; // Recipient To information var recipientsTo = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, false, false); // Recipient CC information var recipientsCc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, false, false); #region Generate and save html // Get Html HtmlGenerator oHtmlGenerator = new HtmlGenerator(); oHtmlGenerator.Title = $"Subject: {msg.Subject}"; oHtmlGenerator.AddParagraphBodyItem($"File Name: {msg.FileName}"); oHtmlGenerator.AddParagraphBodyItem($"From: {from}"); oHtmlGenerator.AddParagraphBodyItem($"Sent On: {(sentOn.HasValue ? sentOn.Value.ToString("MM/dd/yyyy HH:mm") : "")}"); oHtmlGenerator.AddParagraphBodyItem($"To: {recipientsTo}"); oHtmlGenerator.AddParagraphBodyItem($"Subject: {msg.Subject}"); if (!string.IsNullOrEmpty(recipientsCc)) { oHtmlGenerator.AddParagraphBodyItem($"CC: {recipientsCc}"); } oHtmlGenerator.AddRawBodyItem("<hr/>"); var msgBodySplitted = msg.BodyText.Split("\n".ToCharArray()); foreach (var itmBody in msgBodySplitted) { oHtmlGenerator.AddParagraphBodyItem(itmBody); } // Generate Html oHtmlGenerator.SaveHtml("result.html"); #endregion using (HtmlToPdfConverter converter = new HtmlToPdfConverter()) { converter.PageSize = PaperKind.A4; converter.Orientation = Bytescout.PDF.Converters.PaperOrientation.Portrait; converter.ConvertHtmlToPdf("result.html", "result.pdf"); // Open result document in default associated application (for demo purpose) ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf"); processStartInfo.UseShellExecute = true; Process.Start(processStartInfo); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); } }
private void LoadMsgToTree(MsgReader.Outlook.Storage.Message message, TreeNode rootNode) { try { rootNode.Text = message.Subject; rootNode.Nodes.Add("Subject: " + message.Subject); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); try { doc.LoadHtml(message.BodyHtml); } catch { } var bodyNodeHtml = doc.DocumentNode.SelectSingleNode("//body"); TreeNode bodyNode = rootNode.Nodes.Add("Body: " + GetShortMessage(message.BodyText)); bodyNode.Tag = new string[] { bodyNodeHtml != null ? bodyNodeHtml.InnerHtml : message.BodyText, message.BodyRtf }; rootNode.Tag = message.BodyText; TreeNode dateNode = rootNode.Nodes.Add("Received On: " + message.ReceivedOn); dateNode.Tag = message.ReceivedOn; dateNode.Name = "ReceivedOn"; if (!string.IsNullOrEmpty(message.Sender.DisplayName) || !string.IsNullOrEmpty(message.Sender.Email)) { string fromText = message.Sender.DisplayName + "<" + message.Sender.Email + ">"; TreeNode fromNode = rootNode.Nodes.Add("From: " + fromText); fromNode.Tag = fromText; fromNode.Name = "fromNode"; } if (message.Recipients.Count > 1) { TreeNode recipientNode = rootNode.Nodes.Add("Recipients: " + message.Recipients.Count); foreach (MsgReader.Outlook.Storage.Recipient recipient in message.Recipients) { recipientNode.Nodes.Add(recipient.Type + ": " + recipient.Email); } } else if (message.Recipients.Count > 0) { TreeNode recipientNode = rootNode.Nodes.Add("Recipient: " + message.Recipients.First().Email); } if (message.Attachments.Count > 0) { TreeNode attachmentNode = rootNode.Nodes.Add("Attachments: " + message.Attachments.Count); foreach (MsgReader.Outlook.Storage.Attachment.Attachment attachment in message.Attachments) { attachmentNode.Nodes.Add(attachment.FileName + ": " + attachment.Data.Length + "b"); } } if (MessagesTreeView.Nodes.Count > 0 && !UpButton.Enabled && !DownButton.Enabled) { ChangeUpDownButtonsEnable(true); } rootNode.Expand(); } catch (Exception exp) { MessageBox.Show(exp.Message); } }
static void Main(string[] args) { //Diretório onde os arquivos ".msg" se encontram string[] files = Directory.GetFiles(@"C:\\Users\\erik.silva\\Desktop\\Certificados\\"); Console.WriteLine("Acessando o diretório ..."); foreach (var file in files) { Console.WriteLine("Iniciando o Loop em cada arquivo ..."); using (var msg = new MsgReader.Outlook.Storage.Message(file)) { System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); //Faço uma verificação nos arquivos, se não seguir as regras de nomenclatura, já passo direto. //Exemplo em que não é encontrado o RF: Curso realizado na SME -_C12017430718_I190679 //Exemplo em que possuem números com pontuação: Curso realizado na SME -014.261.29_C1HOM21182_I324370 //Campos que não acessam os Anexos var assuntoEmail = msg.Subject; var htmlBody = msg.BodyHtml; var nomeArquivo = msg.GetAttachmentNames(); string numHomologacaoCurso = assuntoEmail.Substring(assuntoEmail.Length - 18, 18); string rfUsuario = nomeArquivo.Substring(0, 10); string connetionString = null; connetionString = "server=10.50.1.222;database=sme_certificados;uid=usr_certificados;pwd=WgpxCufo;"; Console.WriteLine("Conexão ao banco efetuada com sucesso"); string sql = "SELECT COUNT(*) FROM tb_arquivo_certificado WHERE num_homolog_curso = @num_homolog_curso"; using (MySqlConnection cn = new MySqlConnection(connetionString)) { cn.Open(); //lendo os sAnexos foreach (MsgReader.Outlook.Storage.Attachment itmAttachment in msg.Attachments) { //Convertendo para base 64 var oData = itmAttachment.Data; var anexo = Convert.ToBase64String(oData); //Se não existir, crio a pasta temp para armazenar os anexos string caminhoArquivo = @"c:\\temp\\"; if (!Directory.Exists(caminhoArquivo)) { Directory.CreateDirectory(caminhoArquivo); } caminhoArquivo = caminhoArquivo + nomeArquivo; //Jogando de BASE64 para arquivos, para ler o conteúdo do PDF anexo using (System.IO.FileStream stream = System.IO.File.Create(caminhoArquivo)) { System.Byte[] byteArray = System.Convert.FromBase64String(anexo); stream.Write(byteArray, 0, byteArray.Length); } //Se for diferente de 36 caracteres (Padrâo) nem efetuo as validações if (nomeArquivo.Length == 36) { //Iniciando a leitura dos arquivos using (PdfReader reader = new PdfReader(caminhoArquivo)) { for (int pageNo = 1; pageNo <= reader.NumberOfPages; pageNo++) { ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); string textPdf = PdfTextExtractor.GetTextFromPage(reader, pageNo, strategy); textPdf = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(textPdf))); //Localizando o nome do curso int ncFrom = textPdf.IndexOf("Curso ") + "Curso ".Length; int ncTo = textPdf.Replace(" ", "").LastIndexOf(" promovido pelo"); string nomeCurso = textPdf.Substring(ncFrom, ncTo - ncFrom); //Localizando a data de conclusão int dcFrom = textPdf.IndexOf("São Paulo, ") + "São Paulo, ".Length; int dcTo = textPdf.LastIndexOf(".\nPMSP"); string dataConclusaoCurso = textPdf.Substring(dcFrom, dcTo - dcFrom); dataConclusaoCurso = dataConclusaoCurso.Replace(" de", "/").Replace(" ", ""); //Tratando o mês dataConclusaoCurso = RetornaMes(dataConclusaoCurso); //GUID Guid id = Guid.NewGuid(); //Conectando com o banco de dados Console.WriteLine("Conectando no banco"); //Preciso verificar se os casos já existem na tabela using (MySqlCommand cmd = new MySqlCommand(sql, cn)) { cmd.Parameters.AddWithValue("@num_homolog_curso", numHomologacaoCurso); var result = Convert.ToInt32(cmd.ExecuteScalar()); //Só vai inserir caso não exista na tabela if (result == 0) { //insert string queryInsert = "INSERT INTO tb_arquivo_certificado(id,rf,num_homolog_curso,nome_curso,arquivo,dt_conclusao,dt_execucao) VALUES(@id,@rf,@num_homolog_curso,@nome_curso,@arquivo,@dt_conclusao,@dt_execucao)"; using (MySqlCommand cmdInsert = new MySqlCommand(queryInsert, cn)) { cmdInsert.Parameters.Add("@id", MySqlDbType.VarChar).Value = id; cmdInsert.Parameters.Add("@rf", MySqlDbType.VarChar).Value = rfUsuario; cmdInsert.Parameters.Add("@num_homolog_curso", MySqlDbType.VarChar).Value = numHomologacaoCurso; cmdInsert.Parameters.Add("@nome_curso", MySqlDbType.VarChar).Value = nomeCurso; cmdInsert.Parameters.Add("@arquivo", MySqlDbType.MediumText).Value = anexo; cmdInsert.Parameters.Add("@dt_conclusao", MySqlDbType.VarChar).Value = dataConclusaoCurso; cmdInsert.Parameters.AddWithValue("@dt_execucao", DateTime.Now); cmdInsert.ExecuteNonQuery(); } } } } } } } cn.Close(); } } } Console.WriteLine("Excluindo pasta!!"); //Excluindo os arquivos(verificar disponibilidade) if (Directory.Exists(@"c:\\temp\\")) { Directory.Delete(@"c:\\temp\\", true); } Console.WriteLine("Fim do processo!!"); Console.Read(); }
public static bool ConvertFileContentsMSG(TNDDropItem fc) { if (fc.Content == null) { return(false); } using (var message = new MsgReader.Outlook.Storage.Message(new MemoryStream(fc.Content))) { fc.SetProperty("From", message.Sender?.Email); fc.SetProperty("Subject", message.Subject); fc.SetProperty("Text", message.BodyText); // switch (message.Type) // { // case MsgReader.Outlook.Storage.Message.MessageType.Email: // case MsgReader.Outlook.Storage.Message.MessageType.EmailSms: // case MsgReader.Outlook.Storage.Message.MessageType.EmailNonDeliveryReport: // case MsgReader.Outlook.Storage.Message.MessageType.EmailDeliveryReport: // case MsgReader.Outlook.Storage.Message.MessageType.EmailDelayedDeliveryReport: // case MsgReader.Outlook.Storage.Message.MessageType.EmailReadReceipt: // case MsgReader.Outlook.Storage.Message.MessageType.EmailNonReadReceipt: // case MsgReader.Outlook.Storage.Message.MessageType.EmailEncryptedAndMaybeSigned: // case MsgReader.Outlook.Storage.Message.MessageType.EmailEncryptedAndMaybeSignedNonDelivery: // case MsgReader.Outlook.Storage.Message.MessageType.EmailEncryptedAndMaybeSignedDelivery: // case MsgReader.Outlook.Storage.Message.MessageType.EmailClearSignedReadReceipt: // case MsgReader.Outlook.Storage.Message.MessageType.EmailClearSignedNonDelivery: // case MsgReader.Outlook.Storage.Message.MessageType.EmailClearSignedDelivery: // case MsgReader.Outlook.Storage.Message.MessageType.EmailBmaStub: // case MsgReader.Outlook.Storage.Message.MessageType.CiscoUnityVoiceMessage: // case MsgReader.Outlook.Storage.Message.MessageType.EmailClearSigned: // return message.Headers.From // WriteMsgEmail(message, outputFolder, hyperlinks).ToArray(); // case Storage.Message.MessageType.Appointment: // case Storage.Message.MessageType.AppointmentNotification: // case Storage.Message.MessageType.AppointmentSchedule: // case Storage.Message.MessageType.AppointmentRequest: // case Storage.Message.MessageType.AppointmentRequestNonDelivery: // case Storage.Message.MessageType.AppointmentResponse: // case Storage.Message.MessageType.AppointmentResponsePositive: // case Storage.Message.MessageType.AppointmentResponsePositiveNonDelivery: // case Storage.Message.MessageType.AppointmentResponseNegative: // case Storage.Message.MessageType.AppointmentResponseNegativeNonDelivery: // case Storage.Message.MessageType.AppointmentResponseTentative: // case Storage.Message.MessageType.AppointmentResponseTentativeNonDelivery: // return WriteMsgAppointment(message, outputFolder, hyperlinks).ToArray(); // case Storage.Message.MessageType.Contact: // return WriteMsgContact(message, outputFolder, hyperlinks).ToArray(); // case Storage.Message.MessageType.Task: // case Storage.Message.MessageType.TaskRequestAccept: // case Storage.Message.MessageType.TaskRequestDecline: // case Storage.Message.MessageType.TaskRequestUpdate: // return WriteMsgTask(message, outputFolder, hyperlinks).ToArray(); // case Storage.Message.MessageType.StickyNote: // return WriteMsgStickyNote(message, outputFolder).ToArray(); // case Storage.Message.MessageType.Unknown: // throw new MRFileTypeNotSupported("Unsupported message type"); // } return(true); } }
public void DoWork(object obj) //chay Parallel.ForEach { if (obj == null) { return; } List <FileMeta> LstfileMeta = (List <FileMeta>)obj; if (LstfileMeta.Count == 0) { return; } string sPath = MyConfig.GetMailFolder(); foreach (var fileMeta in LstfileMeta) { try { using (var msg = new MsgReader.Outlook.Storage.Message(fileMeta.FullName)) { //msg.Type == MsgReader.Outlook.MessageType.Email //msg.Type == MsgReader.Outlook.MessageType.AppointmentRequest //msg.Type == MsgReader.Outlook.MessageType.EmailNonDeliveryReport // etc Document doc = new Document(); doc.Add(new Field("SentOn", msg.GetSentOnEx(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("ReceivedOn", msg.GetReceivedOnEx(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("Subject", msg.Subject.EmptyIfNullEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Body", msg.BodyText.EmptyIfNullEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("SenderEmailAddress", msg.Sender.Email.EmptyIfNullEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("SenderName", msg.Sender.DisplayName.EmptyIfNullEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("To", msg.GetEmailToEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("CC", msg.GetEmailCcEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Categories", msg.GetCategoryEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("FlagRequest", msg.GetFlagEx(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("Importance", msg.GetImportanceEx(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("AttachmentNames", msg.GetAttachmentNames().EmptyIfNullEx(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("FullFileName", fileMeta.FileNameWithoutPath, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("LastWriteTime", fileMeta.LastWriteTime, Field.Store.YES, Field.Index.NOT_ANALYZED)); Writer.AddDocument(doc); } } catch (Exception ex) { lock (_lockObject) { ConStackLog.Push(ex.Message + "|" + fileMeta.FullName); } } } }