在 c# 中动态分配 ContentId 并发送带有嵌入图像的电子邮件

Posted

技术标签:

【中文标题】在 c# 中动态分配 ContentId 并发送带有嵌入图像的电子邮件【英文标题】:Dynamically assign ContentId and send email with embedded images in c# 【发布时间】:2015-10-16 15:45:03 【问题描述】:

如何在 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);

【问题讨论】:

请提及你的想法@john 【参考方案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 -->
    ...
                      

【讨论】:

以上是关于在 c# 中动态分配 ContentId 并发送带有嵌入图像的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

GMAIL API 在 C# 中发送带附件的电子邮件

C#带cookie Post和Get方式发送数据,保持cookie

C#调用带参动态库时一直报错?

Green Hills Integrity 动态内存分配

将图像嵌入电子邮件 - ContentID 和 ContentLocation 有啥区别?

C# MailTo 带附件?