如何使用.net在邮件正文中嵌入多个图像

本文关键字:图像 正文 net 何使用 | 更新日期: 2023-09-27 18:05:33

我正在编写一个程序,它将在电子邮件正文(HTML)中嵌入多个图像(图表)发送电子邮件给用户。

当我尝试位于这里的样本…当我只嵌入一个图像时,它工作得很好http://www.systemnetmail.com/faq/4.4.aspx。

但是,当我试图使用下面的代码嵌入多个图像时,没有一个图像被嵌入,而是作为附件发送。

public MailMessage MailMessage(Metric metric, DateTime date)
{
    MailMessage msg = new MailMessage();
    msg.From = new MailAddress("test@gmail.com", "User1");
    msg.To.Add(new MailAddress("test@gmail.com"));
    msg.Subject = "Trend for metric: " + metric.Name;
    msg.IsBodyHtml = true;
    // Generate the charts for the given metric
    var charts = this.GenerateCharts(metric, date);
    int i = 0;
    string htmlBody = "<html><body>";
    List<LinkedResource> resources = new List<LinkedResource>();
    foreach (var chart in charts)
    {
        string imageTag = string.Format("<img src=cid:chart{0} /><br>", i);
        htmlBody += imageTag;
        LinkedResource graph = new LinkedResource(chart.Value, "image/jpeg");
        graph.ContentId = "chart" + i;
        resources.Add(graph);
        i++;
    }
    htmlBody += "</body></html>";
    // Alternate view for embedded images
    AlternateView avText = AlternateView.CreateAlternateViewFromString(metric.Name, null, MediaTypeNames.Text.Html);
    AlternateView avImages = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    // Add all the images as linked resources
    resources.ForEach(x => avImages.LinkedResources.Add(x));
    // Add the views for image
    msg.AlternateViews.Add(avText);
    msg.AlternateViews.Add(avImages);

    return msg;
}

我错过了什么线索吗?我检查了同样作为邮件附件发送的。htm文件,html源代码如下:

<html>><body><img src=cid:chart0 /><br><img src=cid:chart1 /><br><img src=cid:chart2/><br><img src=cid:chart3 /><br><img src=cid:chart4 /><br></body></html>

所以问题是如何在html正文中发送多个图像,而不是作为附件。

如何使用.net在邮件正文中嵌入多个图像

当使用System.Net.Mail时,在电子邮件中嵌入图像的另一种方法是

将图像从本地驱动器附加到电子邮件,并为其分配contentID,然后在图像URL中使用此contentID

可以这样做:

var contentID = "Image";
var inlineLogo = new Attachment(@"C:'Desktop'Image.jpg");
inlineLogo.ContentId = contentID;
inlineLogo.ContentDisposition.Inline = true;
inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
msg.IsBodyHtml = true;
msg.Attachments.Add(inlineLogo);
msg.Body = "<htm><body> <img src='"cid:" + contentID + "'"> </body></html>";

首先,您可以尝试使用绝对uri来嵌入图像。下面是来自RFC-2557的例子:

  From: foo1@bar.net
  To: foo2@bar.net
  Subject: A simple example
  Mime-Version: 1.0
  Content-Type: multipart/related; boundary="boundary-example";
          type="text/html"; start="<foo3@foo1@bar.net>"
  --boundary-example
  Content-Type: text/html;charset="US-ASCII"
  Content-ID: <foo3@foo1@bar.net>
  ... text of the HTML document, which might contain a URI
  referencing a resource in another body part, for example
  through a statement such as:
  <IMG SRC="http://www.ietf.cnri.reston.va.us/images/ietflogo.gif" ALT="IETF logo">
  --boundary-example
  Content-Location:
     http://www.ietf.cnri.reston.va.us/images/ietflogo.gif
  Content-Type: IMAGE/GIF
  Content-Transfer-Encoding: BASE64
  R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNvcHlyaWdodCAoQykgMTk5
  NSBJRVRGLiBVbmF1dGhvcml6ZWQgZHVwbGljYXRpb24gcHJvaGliaXRlZC4A
  etc...
  --boundary-example--

你只需要分配LinkedResource。

使用ContentLink属性代替ContentId。

第二个,你可以直接嵌入图像到你的html与"data" URL方案。

    <IMG
    SRC="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw
    AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz
    ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp
    a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl
    ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis
    F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH
    hhx4dbgYKAAA7"
    ALT="Larry">

顺便说一句,你的html标记格式不好。您可能还对" foreach "answers" foreach "感兴趣

我想我知道真正的问题是什么了在这一行

// Alternate view for embedded images
    AlternateView avText = AlternateView.CreateAlternateViewFromString(metric.Name, null, MediaTypeNames.Text.Html);
    AlternateView avImages = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);

正如你所看到的,我的两个视图都被指定为text . html,所以第一个是覆盖下一个,所以我只看到文本和图像作为附件发送

我做了以下更改,它像预期的那样工作

AlternateView avText = AlternateView.CreateAlternateViewFromString(metric.Name, null, **MediaTypeNames.Text.Plain**);
AlternateView avImages = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);

我的替代选项:

首先,一个小扩展:

public static class RegexExtensions
{
    public static string GetPattern(this IEnumerable<string> valuesToSearch)
    {
        return string.Format("({0})", string.Join("|", valuesToSearch));
    }
}

然后从文件夹

中获取图像名称
    private string[] GetFullNamesOfImages()
    {
        string images = Path.Combine(_directoryName, "Images");
        if (!Directory.Exists(images))
            return new string[0];
        return Directory.GetFiles(images);
    }

然后用cid:

替换图像名称
    private string InsertImages(string body)
    {
        var images = GetFullNamesOfImages().Select(Path.GetFileName).ToArray();
        return Regex.Replace(body, "(Images/)?" + images.GetPattern(), "cid:$2", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    }

其中body -为HTML主体,例如,<img src="Images/logo_shadow.png" alt="" style="width: 100%;" />将被<img src="cid:logo_shadow.png" alt="" style="width: 100%;" />取代

然后最后一个动作:添加图像本身到邮件:

    private MailMessage CreateMail(SmtpClient smtp, string toAddress, string body)
    {
        var images = GetFullNamesOfImages();
        string decodedBody = WebUtility.HtmlDecode(body);
        var text = AlternateView.CreateAlternateViewFromString(decodedBody, null, MediaTypeNames.Text.Plain);
        var html = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
        foreach (var image in images)
        {
            html.LinkedResources.Add(new LinkedResource(image, new ContentType("image/png"))
                                     {
                                         ContentId = Path.GetFileName(image)
                                     });
        }

        var credentials = (NetworkCredential) smtp.Credentials;
        var message = new MailMessage(new MailAddress(credentials.UserName), new MailAddress(toAddress))
                      {
                          Subject = "Some subj",
                          Body = decodedBody
                      };
        message.AlternateViews.Add(text);
        message.AlternateViews.Add(html);
        return message;
    }

如果你的图片是在线的,也就是从一个托管站点发送的,我建议你只引用这些图片,把它们的url放在src中。

<!-- using artplastika  examples -->
<IMG SRC="http://www.ietf.cnri.reston.va.us/images/ietflogo.gif" ALT="IETF logo" />

大多数时事通讯使用这种方法,我相信它比嵌入本身更轻,可以消耗更少的资源。

希望能有所帮助

        AlternateView avHtml = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
        LinkedResource inline = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/Images/e1.jpg"), MediaTypeNames.Image.Jpeg);
        inline.ContentId = "1";
        inline.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
        avHtml.LinkedResources.Add(inline);
        LinkedResource inline1 = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/CImages/2.jpg"), MediaTypeNames.Image.Jpeg);
        inline1.ContentId = "2";
        inline1.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
        avHtml.LinkedResources.Add(inline1);
        LinkedResource inline2 = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/Images/3.jpg"), MediaTypeNames.Image.Jpeg);
        inline2.ContentId = "3";
        inline2.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
        avHtml.LinkedResources.Add(inline2);
        LinkedResource inline3 = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/Content/Images/4.jpg"), MediaTypeNames.Image.Jpeg);
        inline3.ContentId = "4";
        inline3.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
        avHtml.LinkedResources.Add(inline3);
        MailMessage mail = new MailMessage();
        mail.AlternateViews.Add(avHtml);
HTML:

       <img src="cid:1" alt="" />
       <img src="cid:2" alt="" />
       <img src="cid:3" alt="" /`
       <img src="cid:4" alt="" />

尝试如下:

private static ICollection<LinkedResource> GetLinkedResources()
{
    var linkedResources = new List<LinkedResource>();
    linkedResources.Add(new LinkedResource(@"imagepath")
    {
        ContentId = "HeaderId",
        TransferEncoding = TransferEncoding.Base64
    });
    linkedResources.Add(new LinkedResource(@"imagepath")
    {
        ContentId = "MapId",
        TransferEncoding = TransferEncoding.Base64
    });
    return linkedResources;
}

然后你可以像这样调用方法:

 mailMessage.AlternateViews.Add(GetEmbeddedImage(body));