public async Task <IActionResult> FileUpload(List <IFormFile> files) //Create([Bind("ID,sender,subject,body,recieved")] Message message) { var filePath = Path.GetTempFileName(); //rand probably not needed here, can delete when done Random rnd = new Random(); foreach (var formFile in files) { if (formFile.Length > 0) { using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } using (var msg = new MsgReader.Outlook.Storage.Message(filePath)) { //int id = rnd.Next(); var from = msg.GetEmailSender(false, false); var sentOn = msg.SentOn; var sentTo = msg.GetEmailRecipients(Storage.Recipient.RecipientType.To, false, false); var sentTocc = msg.GetEmailRecipients(Storage.Recipient.RecipientType.Cc, false, false); var subject = msg.Subject; var htmlBody = msg.BodyText; //can change to bodyHTLM is want that instead var headerSender = msg.Headers.From.Address; var headerSenderValid = msg.Headers.From.HasValidMailAddress; Console.Write("test"); var senderDomain = from.Split("@")[1]; //IP below is not currently sent in to the model, can easily change if needed //var senderIP = msg.Headers.Received.Last().Names[0]; var email = new Message(/*id,*/ from, sentOn, sentTo, sentTocc, subject, htmlBody, headerSender, senderDomain, headerSenderValid); Console.WriteLine(email); if (ModelState.IsValid) { _context.Add(email); await _context.SaveChangesAsync(); Console.WriteLine("context chanhed to add msg details"); } } } } return(RedirectToAction(nameof(Index))); /*return View(message)*/; }
public IEnumerable <OutlookMessage> GetOutlookMessages(string path) { using (var msg = new MsgReader.Outlook.Storage.Message(@"C:\test\test.msg")) { var from = msg.Sender; var sentOn = msg.SentOn; var recipientsTo = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, false, false); var recipientsCc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, false, false); var subject = msg.Subject; var htmlBody = msg.BodyHtml; // etc... } return(new List <OutlookMessage>()); }
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(); } }
private bool parseUsingMsgReader(string path) { if (!File.Exists(path)) { // TODO: logging return(false); } MsgReader.Outlook.Storage.Message msg = null; try { msg = new MsgReader.Outlook.Storage.Message(path); } catch (Exception ex) { return(false); } using (msg) { ParsedMsgMessage parsedMsgMessage = new ParsedMsgMessage(); parsedMsgMessage.Sender = msg.Sender.DisplayName + "<" + msg.Sender.Email + ">"; parsedMsgMessage.To_formatted = msg.GetEmailRecipients(Storage.Recipient.RecipientType.To, false, false); parsedMsgMessage.CC_formatted = msg.GetEmailRecipients(Storage.Recipient.RecipientType.Cc, false, false); parsedMsgMessage.Subject = msg.Subject; parsedMsgMessage.BodyHtml = msg.BodyHtml; parsedMsgMessage.BodyRtf = msg.BodyRtf; parsedMsgMessage.BodyText = msg.BodyText; parsedMsgMessage.AttachementNames_formatted = msg.GetAttachmentNames(); //this.headers = msg.Headers; parsedMsgMessage.SentOn = msg.SentOn; parsedMsgMessage.ReceivedOn = msg.ReceivedOn; parsedMsgMessage.CreationTime = msg.CreationTime; parsedMsgMessage.LastModificationTime = msg.LastModificationTime; foreach (var msgAttachment in msg.Attachments) { MsgReader.Outlook.Storage.Attachment ss; if (msgAttachment is MsgReader.Outlook.Storage.Attachment) { var attach = (MsgReader.Outlook.Storage.Attachment)msgAttachment; parsedMsgMessage.AttachementNames.Add(attach.FileName); } else if (msgAttachment is MsgReader.Outlook.Storage.Message) { var attach = (MsgReader.Outlook.Storage.Message)msgAttachment; parsedMsgMessage.AttachementNames.Add(attach.FileName); } } //extractAndConvertAttachements(path); // msgAsText = $@" //FROM: {from} //SENT ON: {sentOn} //TO: {recipientsTo} //CC: {recipientsCC} //SUBJECT: {subject} //HTMLBODY: {htmlBody} //RTFBODY: {rtfBody} //TXTBODY: {textBody} //ATTN: {attachementNames} //CREATIONTIME: {creationTime} //RECV_ON: {receivedOn} //MOD_DATE: {lastModificationTime}"; } return(true); }
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("HtmlSampleEmail.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"; // If you wish to load an existing document uncomment the line below and comment the Add page section instead // pdfDocument.Load(@".\existing_document.pdf"); // 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 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 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); } // 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 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); }
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(); } }