[c#]获取exchange中的图片
摘要
在exchange 2007或者2010中获取的邮件内容为html标签格式,也就是一个页面。如果里面含有img标签,你会发现img标签的src属性为cid:xxxxxxxxxxxx的一串字符串,并不是url,这时候就造成页面上图片显示不出来。
解决办法
在网上找了一种解决办法。
原文地址:http://stackoverflow.com/questions/6650842/ews-exchange-2007-retrieve-inline-images
首先创建cid的索引
private const string CidPattern = "cid:"; private static HashSet<int> BuildCidIndex(string html) { var index = new HashSet<int>(); var pos = html.IndexOf(CidPattern, 0); while (pos > 0) { var start = pos + CidPattern.Length; index.Add(start); pos = html.IndexOf(CidPattern, start); } return index; }
在索引的基础上封装一个替换的方法
private static void AdjustIndex(HashSet<int> index, int oldPos, int byHowMuch) { var oldIndex = new List<int>(index); index.Clear(); foreach (var pos in oldIndex) { if (pos < oldPos) index.Add(pos); else index.Add(pos + byHowMuch); } } private static bool ReplaceCid(HashSet<int> index, ref string html, string cid, string path) { var posToRemove = -1; foreach (var pos in index) { if (pos + cid.Length < html.Length && html.Substring(pos, cid.Length) == cid) { var sb = new StringBuilder(); sb.Append(html.Substring(0, pos-CidPattern.Length)); sb.Append(path); sb.Append(html.Substring(pos + cid.Length)); html = sb.ToString(); posToRemove = pos; break; } } if (posToRemove < 0) return false; index.Remove(posToRemove); AdjustIndex(index, posToRemove, path.Length - (CidPattern.Length + cid.Length)); return true; }
在获取的item中获取附件
FileAttachment[] attachments = null; var index = BuildCidIndex(sHTMLCOntent); if (index.Count > 0 && item.Attachments.Count > 0) { var basePath = Directory.GetCurrentDirectory(); attachments = new FileAttachment[item.Attachments.Count]; for (var i = 0; i < item.Attachments.Count; ++i) { var type = item.Attachments[i].ContentType.ToLower(); if (!type.StartsWith("image/")) continue; type = type.Replace("image/", ""); var attachment = (FileAttachment)item.Attachments[i]; var cid = attachment.ContentId; var filename = cid + "." + type; var path = Path.Combine(basePath, filename); if(ReplaceCid(index, ref sHTMLCOntent, cid, path)) { // only load images when they have been found attachment.Load(path); attachments[i] = attachment; } } }
-
博客地址:http://www.cnblogs.com/wolf-sun/
博客版权:如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。