0

we are trying to send email by placing the images with in the mail body.but it is not showing in the received email.here is my code to attach the images to my email body.Please help me to solve the issue.

 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);
Srinivas Ch
  • 1,202
  • 2
  • 19
  • 34

1 Answers1

0

Another option for building emails is to use RazorEngine (you have to install it on your project).

You can have something like below:

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

where param1 is the path to the cshtml and param2 represents the model.

You can even have a particular picture for each email by keeping the path to the image in a model property.

Have a nice day!

Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
Marius J.
  • 1
  • 1