2017-01-11 26 views
0

我們試圖通過將圖像放在郵件正文中發送電子郵件,但它未顯示在收到的電子郵件中。我的代碼將圖像附加到我的電子郵件正文請幫我解決這個問題。如何通過運行時郵件正文嵌入圖像

string Body = mainContent.ToString(); 
      AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body.ToString(), null, "text/html"); 

      HtmlDocument document = new HtmlDocument(); 
      document.LoadHtml(Body); 
      document.DocumentNode.Descendants("img") 
           .Where(e => 
           { 
            string src = e.GetAttributeValue("src", null) ?? ""; 
            return !string.IsNullOrEmpty(src) && !src.StartsWith("data:image"); 
           }) 
           .ToList() 
           .ForEach(x => 
           { 
            string currentSrcValue = x.GetAttributeValue("src", null); 

            string contentId = Guid.NewGuid().ToString(); 
            LinkedResource inline = new LinkedResource(System.Web.Hosting.HostingEnvironment.MapPath("~"+currentSrcValue)); 
            inline.ContentId = contentId; 
            inline.TransferEncoding = TransferEncoding.Base64; 

            x.SetAttributeValue("src", "cid:" + inline.ContentId); 
            htmlView.LinkedResources.Add(inline); 
           }); 


      string result = document.DocumentNode.OuterHtml; 


      mail.IsBodyHtml = true; 
      htmlView = AlternateView.CreateAlternateViewFromString(result.ToString(), null, "text/html"); 
      mail.AlternateViews.Add(htmlView); 
+0

用於在電子郵件中嵌入圖像的簡單方法請參閱[此StackOverflow鏈接](http://stackoverflow.com/a/30126266/2803565) –

回答

0

另一種選擇建立電子郵件是使用RazorEngine(你必須對你的項目安裝)。

你可以有類似下面:

mail.Body = Razor.Parse(param1, param2); 

其中參數1是路徑CSHTML和參數2表示的模型。

通過在模型屬性中保留圖像的路徑,您甚至可以爲每封電子郵件提供特定圖片。

祝您有美好的一天!

相關問題