簡體   English   中英

將.jpg圖像(base64字符串表示形式)嵌入到電子郵件正文(System.Net.Mail)中

[英]Embedding .jpg image (base64 string representation) into email message body (System.Net.Mail)

我能夠將jpg圖片正確轉換為base64String。 但是我在使用轉換后的圖像字符串和LinkedResource將其嵌入電子郵件正文時遇到了麻煩。 該圖像作為電子郵件正文中的“未找到圖像”圖標出現。 任何幫助將不勝感激。

我已經在此鏈接上關注示例: 遍歷html字符串以查找所有img標簽並替換src屬性值

我正在使用HtmlAgilityPack(nuget包)通過以下代碼定位img元素。

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; 
    }

傳遞給函數的html參數包含一個img標簽,其src等於圖像的base64編碼。 從此函數返回的內容將分配給電子郵件的message.body。

通過遵循其他帖子中的解決方案來解決。 如果外面有人試圖做同樣的事情並且遇到像我一樣的麻煩,我將在下面發布代碼。

基本上,我必須將html中的LinkedResource(圖像)保存到一個列表,然后遍歷該列表,並將所有圖像添加到foreach循環之外的AlternateView中。

 // Embeds image to properly show in Email. Image element to show in html will not work in Email body. 
                        // https://stackoverflow.com/questions/39785600/iterate-through-an-html-string-to-find-all-img-tags-and-replace-the-src-attribut
                        // XmlAgilityPack gets used here to parse html string. 
                        List<LinkedResource> linkedResources = new List<LinkedResource>(); 
                        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                        int increment = 0; 
                        doc.LoadHtml(tempMsg);
                        doc.DocumentNode.Descendants("img").Where(z =>
                            {
                                string src = z.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 id = Guid.NewGuid().ToString();
                                increment++;

                                LinkedResource inlineImage = new LinkedResource(new MemoryStream(imageData), System.Net.Mime.MediaTypeNames.Image.Jpeg);
                                inlineImage.ContentType.Name = "img " + increment; 
                                inlineImage.ContentId = id;
                                inlineImage.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                                x.SetAttributeValue("src", "cid:" + inlineImage.ContentId);
                                linkedResources.Add(inlineImage);
                            });

                        // Append multiple images from template to email message.
                        // https://stackoverflow.com/questions/7048758/how-to-embed-multiple-images-in-email-body-using-net
                        // Write html to message.body 
                        AlternateView altView = AlternateView.CreateAlternateViewFromString(doc.DocumentNode.OuterHtml, null, "text/html");
                        linkedResources.ForEach(x=>altView.LinkedResources.Add(x));
                        message.AlternateViews.Add(altView);

                        String[] attachments = txtAttachFiles.Text.Split(';');
                        foreach (String filename in attachments)
                        {
                            if (File.Exists(filename))
                            {
                                Attachment attachment = new Attachment(filename);
                                message.Attachments.Add(attachment);
                            }
                        }

                        // loop is set to 1 in the app.config file so technically this for loop is not needed, but will keep this loop just in case. 
                        for (int loop = 0; loop < Convert.ToInt32(ConfigurationManager.AppSettings["loop"]); loop++)
                        {
                            SmtpClient smtp = new SmtpClient();
                            smtp.Host = ConfigurationManager.AppSettings["mailHost"];
                            smtp.Port = Int32.Parse(ConfigurationManager.AppSettings["mailPort"]);
                            smtp.UseDefaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["mailDefaultCredentials"]);
                            smtp.Send(message);
                        }
                    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM