我正在编写一个程序,该程序向电子邮件正文(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正文中发送多个图像,而不是作为附件发送。

最佳答案

使用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>";

关于c# - 如何使用.NET在电子邮件正文中嵌入多个图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7048758/

10-14 17:19
查看更多