I am able to convert a jpg image to base64String properly. But I am having trouble using that converted image string and LinkedResource to to embed it in an email body. The image comes up as an image not found icon in the email body. Any help would be greatly appreciated.
I've followed the example at this link: Iterate through an html string to find all img tags and replace the src attribute values
I am using HtmlAgilityPack (nuget package) to target the img element with the code below.
private string embedImageInMail(string html)
{
HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
doc.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);
currentSrcValue = currentSrcValue.Split(',')[1]; //Base64 part of string
byte[] imageData = Convert.FromBase64String(currentSrcValue);
string contentId = Guid.NewGuid().ToString();
using (MemoryStream ms = new MemoryStream(imageData))
{
LinkedResource inline = new LinkedResource(ms, "image/jpeg");
inline.ContentId = contentId;
inline.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
x.SetAttributeValue("src", "cid:" + inline.ContentId);
}
});
return doc.DocumentNode.OuterHtml;
}
The html parameter passed the function contains an img tag with src equal to the base64 encoding of the image. What gets returned from this function, gets assigned to message.body of the email.