C# How to obtain cid (content id) from url in a <img src="url.jpg" /> tag
I have to send a Multipart MailMessage, with its body being created starting from an html page. The problem is that i have to "translate" the image tag written this way
<img src="url.jpg" />
to a multipart tag of this kind
<img src="cid:imageid" />
Considering that i have to catch every image url and create a new LinkedResource instance for everyone of it before doing this text replacing, do you know if there is any instrument开发者_运维技巧 that do this work for me?
I am using HtmlAgilityPack which makes replacing img src values quite easy:
Dictionary<string, string> cids = new Dictionary<string, string>();
int imgCount = 0;
HtmlDocument doc = new HtmlDocument();
doc.Load(htmlFilename, System.Text.Encoding.UTF8);
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//img"))
{
HtmlAttribute att = link.Attributes["src"];
Console.Write("img src = " + att.Value);
if (!cids.ContainsKey(att.Value))
{
cids[att.Value] = imgCount.ToString() + "." + GetRandomString(10) + "@domain.com";
imgCount++;
}
att.Value = "cid:" + cids[att.Value];
Console.WriteLine(" became " + att.Value);
}
StringWriter sw = new StringWriter();
doc.Save(sw);
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(sw.ToString(), System.Text.Encoding.GetEncoding("utf-8"), "text/html");
After this you have to iterate the cids collection and load and attach each file as a linked resource, setting ContentID to the cid value just set.
I am new to this forum and using the MS Outlook object library. Well, I am also stuck with this stupid problem since long. I remember reading about it a long time ago but couldnt find that post again.
Anyway here is what you can do at this moment, this is what I am doing too (Please accept the answer in VB instead of C#)
<Code>
EmailItem = Mailitem
EmailItem.HTMLBODY = </img src = "SOMETHING.jpg" ...../>
EmailItem.Save
EmailItem.HTMLBODY >>> Read this text and parse it for CID of the image tag.
</Code>
As soon as you save it, it is converted to CID (A unique content ID is given to it). Parse it through and reconstruct your HTML. This is a long way round, but a poosible way out of this problem now.
Also, if the image is hosted on a public network no need to change it to CID it will be automatically done when you send this email.
Hope this solves your problem or may be give you an idea atleast.
Regards Virender
精彩评论