public string CreateFile(MimeMessage mailMessageEx) { if (mailMessageEx == null) { throw new ArgumentNullException(nameof(mailMessageEx)); } var tempDir = CreateUniqueTempDirectory(); var visitor = new HtmlPreviewVisitor(tempDir); mailMessageEx.Accept(visitor); string htmlFile = Path.Combine(tempDir, "index.html"); _logger.Verbose("Writing HTML Preview file {HtmlFile}", htmlFile); File.WriteAllText(htmlFile, visitor.HtmlBody, Encoding.Unicode); return(htmlFile); }
public ActionResult GetAttachment([FromRoute] Guid id, [FromQuery] string attachmentid) { if (Guid.Empty == id) { return(this.BadRequest()); } var mail = this.mailRepository.Get(id); if (mail == null) { return(this.NotFound()); } using var ms = new MemoryStream(mail.RawEmail); ms.Position = 0; var message = MimeMessage.Load(ms); var visitor = new HtmlPreviewVisitor(); message.Accept(visitor); var attachment = message.Attachments.FirstOrDefault(a => a.IsAttachment && (a.ContentId != null? a.ContentId : a.ContentDisposition.FileName?.GetHashCode().ToString()) == attachmentid); if (attachment == null) { return(NotFound()); } var attachmentStream = ParseAttachment(attachment); attachmentStream.Position = 0; var result = new FileStreamResult(attachmentStream, attachment.ContentType.MimeType); result.FileDownloadName = attachment.ContentDisposition.FileName; return(result); }
private static MimeEntity GetEmailFile(string strFullFilePath, string strEmailFileName, string ConnectionString) { GeneralSettings objGeneralSettings = new GeneralSettings(ConnectionString); MimeEntity objMimeEntity = null; if (objGeneralSettings.StorageFileType == "AzureStorage") { CloudStorageAccount storageAccount = null; CloudBlobContainer cloudBlobContainer = null; // Retrieve the connection string for use with the application. string storageConnectionString = objGeneralSettings.AzureStorageConnection; // Check whether the connection string can be parsed. if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount)) { // Ensure there is a AdefHelpDesk Container CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); cloudBlobContainer = cloudBlobClient.GetContainerReference("adefhelpdesk-files"); CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(strFullFilePath); // Download cloudBlockBlob.FetchAttributesAsync().Wait(); long fileByteLength = cloudBlockBlob.Properties.Length; byte[] fileContent = new byte[fileByteLength]; for (int i = 0; i < fileByteLength; i++) { fileContent[i] = 0x20; } cloudBlockBlob.DownloadToByteArrayAsync(fileContent, 0).Wait(); using (MemoryStream memstream = new MemoryStream(fileContent)) { var message = MimeMessage.Load(memstream); var visitor = new HtmlPreviewVisitor(); message.Accept(visitor); // Loop through attachments foreach (var item in visitor.Attachments) { if (item.ContentDisposition.FileName != null) { if (item.ContentDisposition.FileName == strEmailFileName) { return(item); } } } } } else { throw new Exception("AzureStorage configured but AzureStorageConnection value cannot connect."); } } else { using (var fileContents = System.IO.File.OpenRead(strFullFilePath)) { var message = MimeMessage.Load(fileContents); var visitor = new HtmlPreviewVisitor(); message.Accept(visitor); // Loop through attachments foreach (var item in visitor.Attachments) { if (item.ContentDisposition.FileName != null) { if (item.ContentDisposition.FileName == strEmailFileName) { return(item); } } } } } return(objMimeEntity); }
private async void EmailList_ItemClick(object sender, ItemClickEventArgs e) { if (EmailList.SelectionMode == ListViewSelectionMode.Multiple) { return; } if (e.ClickedItem is EmailItem Email) { if (Email == LastSelectedItem) { return; } LastSelectedItem = Email; //建立HtmlPreviewVisitor的实例以解析邮件中的HTML内容 HtmlPreviewVisitor visitor = new HtmlPreviewVisitor(ApplicationData.Current.TemporaryFolder.Path); Email.Message.Accept(visitor); if (Email.FileEntitys.Count() != 0) { EmailDetail.ThisPage.FileExpander.Visibility = Visibility.Visible; EmailDetail.ThisPage.FileCollection.Clear(); foreach (var Entity in Email.Message.Attachments) { EmailDetail.ThisPage.FileCollection.Add(new EmailAttachment(Entity)); } } else { EmailDetail.ThisPage.FileExpander.IsExpanded = false; EmailDetail.ThisPage.FileExpander.Visibility = Visibility.Collapsed; } if (EmailDetail.ThisPage.WebBrowser == null) { //为获得最大的流畅性能,将WebView控件设置为具有单独的进程执行 EmailDetail.ThisPage.WebBrowser = new WebView(WebViewExecutionMode.SeparateProcess) { Visibility = Visibility.Collapsed }; EmailDetail.ThisPage.Gr.Children.Add(EmailDetail.ThisPage.WebBrowser); EmailDetail.ThisPage.WebBrowser.SetValue(Grid.RowProperty, 1); } if (EmailDetail.ThisPage.WebBrowser.Visibility == Visibility.Collapsed) { EmailDetail.ThisPage.WebBrowser.Visibility = Visibility.Visible; EmailDetail.ThisPage.CommandBarContorl.Visibility = Visibility.Visible; } //将解析出来的HTML交由WebBrowser进行读取解析呈现 EmailDetail.ThisPage.WebBrowser.NavigateToString(visitor.HtmlBody); if (Email.IsNotSeenIndicator == 1) { await Email.SetSeenIndicatorAsync(Visibility.Collapsed); for (int i = 0; i < EmailNotSeenItemCollection.Count; i++) { if (EmailNotSeenItemCollection[i].Id == Email.Id) { EmailNotSeenItemCollection.RemoveAt(i); } } } } }
/// <summary> /// 异步获取邮件信息 /// </summary> /// <param name="action">获取回调</param> /// <param name="number">获取多少条</param> /// <returns></returns> public async Task mailAsync(Action <EmailListView, int, int> callBack, int?number) { using (var client = clientService) { try { var inbox = client.Inbox; inbox.Open(FolderAccess.ReadOnly); if (inbox.Count > 0) { var total = inbox.Count - 1; var thisNumber = 1; for (int i = total; i >= 0; i--) { var message = inbox.GetMessage(i); var filePath = AttachmentPath + message.MessageId + "\\"; var files = new List <string>(); foreach (MimeEntity attachment in message.Attachments) { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name; var lastName = filePath + fileName; if (!File.Exists(lastName)) { using (var stream = File.Create(filePath + fileName)) { if (attachment is MessagePart) { var rfc822 = (MessagePart)attachment; rfc822.Message.WriteTo(stream); } else { var part = (MimePart)attachment; part.Content.DecodeTo(stream); } } } files.Add(lastName.Replace(filePath, string.Empty)); } var address = message.From.Select(x => (MailboxAddress)x).First(); var Visitor = new HtmlPreviewVisitor(AttachmentPath); message.Accept(Visitor); var model = new EmailListView { FromEmail = address.Address, Title = message.Subject, SendTime = message.Date.ToString("yyyy-MM-dd HH:mm:ss"), MessageId = message.MessageId, Body = message.TextBody, Html = Visitor.HtmlBody, MainEmail = EmailManger.Email, Mark = 0, Files = string.Join(",", files) }; await Task.Run(() => callBack(model, thisNumber, inbox.Count)).ConfigureAwait(false); if (number != null) { if (number - thisNumber <= 0) { return; } } thisNumber++; } } } catch (Exception ex) { client.Disconnect(true); throw ex; } } }
private static void SetEmailContents(string FileName, int intAttachmentId, string strFullFilePath, string ConnectionString, ref DTOTaskDetail objDTOTaskDetail) { GeneralSettings objGeneralSettings = new GeneralSettings(ConnectionString); if (objGeneralSettings.StorageFileType == "AzureStorage") { CloudStorageAccount storageAccount = null; CloudBlobContainer cloudBlobContainer = null; // Retrieve the connection string for use with the application. string storageConnectionString = objGeneralSettings.AzureStorageConnection; // Check whether the connection string can be parsed. if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount)) { // Ensure there is a AdefHelpDesk Container CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); cloudBlobContainer = cloudBlobClient.GetContainerReference("adefhelpdesk-files"); CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(FileName); // Download cloudBlockBlob.FetchAttributesAsync().Wait(); long fileByteLength = cloudBlockBlob.Properties.Length; byte[] fileContent = new byte[fileByteLength]; for (int i = 0; i < fileByteLength; i++) { fileContent[i] = 0x20; } cloudBlockBlob.DownloadToByteArrayAsync(fileContent, 0).Wait(); using (MemoryStream memstream = new MemoryStream(fileContent)) { var message = MimeMessage.Load(memstream); var visitor = new HtmlPreviewVisitor(); message.Accept(visitor); objDTOTaskDetail.emailDescription = Utility.CleanOutlookFontDefinitions(visitor.HtmlBody); // Add attachments (if any) objDTOTaskDetail.colDTOAttachment = new List <DTOAttachment>(); foreach (var item in visitor.Attachments) { if (item.ContentDisposition.FileName != null) { DTOAttachment objDTOAttachment = new DTOAttachment(); objDTOAttachment.attachmentID = intAttachmentId; objDTOAttachment.attachmentPath = "EML"; objDTOAttachment.userId = "-1"; objDTOAttachment.fileName = item.ContentDisposition.FileName; objDTOAttachment.originalFileName = strFullFilePath; objDTOTaskDetail.colDTOAttachment.Add(objDTOAttachment); } } } } else { throw new Exception("AzureStorage configured but AzureStorageConnection value cannot connect."); } } else { using (var fileContents = System.IO.File.OpenRead(strFullFilePath)) { var message = MimeMessage.Load(fileContents); var visitor = new HtmlPreviewVisitor(); message.Accept(visitor); objDTOTaskDetail.emailDescription = Utility.CleanOutlookFontDefinitions(visitor.HtmlBody); // Add attachments (if any) objDTOTaskDetail.colDTOAttachment = new List <DTOAttachment>(); foreach (var item in visitor.Attachments) { if (item.ContentDisposition.FileName != null) { DTOAttachment objDTOAttachment = new DTOAttachment(); objDTOAttachment.attachmentID = intAttachmentId; objDTOAttachment.attachmentPath = "EML"; objDTOAttachment.userId = "-1"; objDTOAttachment.fileName = item.ContentDisposition.FileName; objDTOAttachment.originalFileName = strFullFilePath; objDTOTaskDetail.colDTOAttachment.Add(objDTOAttachment); } } } } }
private MailViewModel MapMailToMailViewModel(Mail mail, bool transformMimeMessage) { if (mail == null) { return(new MailViewModel()); } string rawEmail = string.Empty; string renderedEmail = string.Empty; IEnumerable <AttachmentViewModel> attachements = new List <AttachmentViewModel>(); if (transformMimeMessage && mail.RawEmail != null && mail.RawEmail.Length > 0) { using var ms = new MemoryStream(mail.RawEmail); ms.Position = 0; var message = MimeMessage.Load(ms); var visitor = new HtmlPreviewVisitor(); message.Accept(visitor); int attachment = 1; attachements = message.Attachments.Where(a => a.IsAttachment).Select(a => new AttachmentViewModel { Id = a.ContentId != null ? a.ContentId : a.ContentDisposition.FileName?.GetHashCode().ToString(), Filename = !string.IsNullOrWhiteSpace(a.ContentDisposition?.FileName) ? a.ContentDisposition?.FileName : $"Attachement {attachment++}", Size = a.ContentDisposition.Size.HasValue ? a.ContentDisposition.Size.Value : ParseAttachment(a).Length, MimeType = a.ContentType.MimeType }).ToList(); renderedEmail = visitor.HtmlBody; using (var msEml = new MemoryStream()) { message.WriteTo(msEml); msEml.Position = 0; StreamReader reader = new StreamReader(msEml); rawEmail = reader.ReadToEnd(); } } return(new MailViewModel { HtmlBody = !string.IsNullOrWhiteSpace(mail.HtmlBody) ? mail.HtmlBody.Trim() : string.Empty, TextBody = !string.IsNullOrWhiteSpace(mail.TextBody) ? mail.TextBody.Trim() : string.Empty, RenderedHtml = PrettifyHtml(renderedEmail.Trim()), RawEmail = rawEmail.Trim(), From = mail.From, MailId = mail.MailId, ReceiveDate = mail.ReceiveDate, Status = mail.Status, Subject = mail.Subject, To = mail.To, MailboxId = mail.MailboxId, Attachements = attachements }); }