动态分配ContentId并使用c#中的嵌入式图像发送电子邮件

时间:2015-07-26 11:30:06

标签: c# email razor model-view-controller

如何在c#中动态分配带有内容id的src How to embed multiple images in email body using .NET 但没有好主意。 当我提交然后我将能够获得html源以及如何动态分配cid

>     > 
>     > <html>><body><img src="~/Upload/1.jpg"><br><img src="~/Upload/1.jpg" /><br><img
>          src="~/Upload/3.jpg"/><br><br>
>     >    thanks!!!</body></html>

需要转换
我想发送包含多个图片的电子邮件

 <html>><body><img src=cid:c1 /><br><img src=cid:c2 /><br><img
    src=cid:c3/><br><br>


   thanks!!!</body></html>

然后

        if (htmlString == null) return null;
        var doc = new HtmlDocument();
        doc.LoadHtml(htmlString);
        HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
        if (nodes == null) return null;
        foreach (HtmlNode node in nodes)
        {
            if (node.Attributes.Contains("src"))
            {
                string data = node.Attributes["src"].Value;
                string base64Data = Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
                if (base64Data != "")
                {
                    string cid = Guid.NewGuid().ToString();
                    byte[] binData = Convert.FromBase64String(base64Data);
                    var stream = new MemoryStream(binData);
                    string contenttype = "image/" +
                                         Regex.Match(data, @"data:image/(?<type>.+?);(?<data>.+)").Groups["type"]
                                             .Value;
                    var inline = new Attachment(stream, new ContentType(contenttype));
                    inline.ContentDisposition.Inline = true;
                    inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
                    inline.ContentId = cid;
                    inline.ContentType.MediaType = contenttype;
                   mailMessage.Attachments.Add(inline);
                    node.Attributes["src"].Value = "cid:" + cid;
                }
            }

任何好主意动态分配和动态添加链接资源和替代视图, 给定的代码适用于静态情况

string path = System.Web.HttpContext.Current.Server.MapPath("~/images/Logo.jpg"); // my logo is placed in images folder
        //var path=""
        var logo = new LinkedResource(path);
        logo.ContentId = "companylogo";
        logo.ContentType = new ContentType("image/jpeg");
        //now do the HTML formatting
        AlternateView av1 = AlternateView.CreateAlternateViewFromString(
              "<html><body><img src=cid:companylogo/>" +
              "<br></body></html>" + strMailContent,
              null, MediaTypeNames.Text.Html);

        //now add the AlternateView
        av1.LinkedResources.Add(logo);

        //now append it to the body of the mail
        msg.AlternateViews.Add(av1);

1 个答案:

答案 0 :(得分:1)

以下是适合您的完整解决方案。

string inputHtmlContent = "<Your Html Content containing images goes here>";
                        string outputHtmlContent = string.Empty;
                        var myResources = new List<LinkedResource>();

                        if ((!string.IsNullOrEmpty(inputHtmlContent)))
                        {

                            var doc = new HtmlDocument();
                            doc.LoadHtml(inputHtmlContent);
                            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
                            if (nodes !=null)
                            {
                                foreach (HtmlNode node in nodes)
                                {
                                    if (node.Attributes.Contains("src"))
                                    {
                                        string data = node.Attributes["src"].Value;
                                        string imgPath = System.Web.HttpContext.Current.Server.MapPath(data);
                                        var imgLogo = new LinkedResource(imgPath);
                                        imgLogo.ContentId = Guid.NewGuid().ToString();
                                        imgLogo.ContentType = new ContentType("image/jpeg");
                                        myResources.Add(imgLogo);
                                        node.Attributes["src"].Value = string.Format("cid:{0}", imgLogo.ContentId);
                                        outputHtmlContent = doc.DocumentNode.OuterHtml;
                                    }
                                }
                            }
                            else
                            {
                                outputHtmlContent = inputHtmlContent;
                            }
                            AlternateView av2 = AlternateView.CreateAlternateViewFromString(outputHtmlContent,
                                null, MediaTypeNames.Text.Html);
                            foreach (LinkedResource linkedResource in myResources)
                            {
                                av2.LinkedResources.Add(linkedResource);
                            }
        var msg = new MailMessage();
                        msg.AlternateViews.Add(av2);
                        msg.IsBodyHtml = true;
    <-- Enter Other required Informations and send mail -->
    ...
                      }