How to embed multiple images in email body using .NET

user330612 picture user330612 · Aug 13, 2011 · Viewed 52.3k times · Source

I'm writing a program that sends emails to users with multiple images (charts) embedded in the Email message body (HTML).

When I tried the sample located here..which worked well when I have to embed only one image http://www.systemnetmail.com/faq/4.4.aspx.

But, when i tried to embed multiple images using the below code, none of the images are being embedded , instead they are sent as attachments.

public MailMessage MailMessage(Metric metric, DateTime date)
{
    MailMessage msg = new MailMessage();
    msg.From = new MailAddress("[email protected]", "User1");
    msg.To.Add(new MailAddress("[email protected]"));
    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;
}

Any clues as what I'm missing? I checked the .htm file which is also sent as attachment with the email, and html source looks as follows:

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

So the Q is how to send multiple images in the html body , not as attachment.

Answer

Jagan picture Jagan · Oct 2, 2013

The other way to embed images in E-mail when using System.Net.Mail is

Attach image from local drive to email and assign a contentID to it and later use this contentID in the image URL.

This can be done by:

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