Embedding Multiple Images in Email Displays only Last Image C#

339 views Asked by At

I need to embed 5 links in a row with images in a MailMessage using C#. The problem is only the last embedded image displays in the email. The result I need is this:

enter image description here

Here is what displays in the delivered email:

enter image description here

Here is my code:

public void SendMail()
{
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;

    mail.AlternateViews.Add(GetEmbeddedImage(images));
    
    ......
}
        

    private AlternateView GetEmbeddedImage(List<string> images)
    {

        AlternateView alternateView =  null;
        string body = "";
        string link = @"<a href='http://localhost:55148/Support/Management/Index'>";

        for (int i = 0; i < images.Count; i++)
        {
            string filepath = images[i];
            LinkedResource res = new LinkedResource(filepath, MediaTypeNames.Image.Jpeg);
            res.ContentId = Guid.NewGuid().ToString();
            body = body + link + @"<img src='cid:" + res.ContentId + @"'/></a>";
            alternateView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
            alternateView.LinkedResources.Add(res);
        }
       
        return alternateView;
    }
1

There are 1 answers

0
Rani Radcliff On

I figured it out. I don't know why it made a difference, but I collected the LinkedResources into a list and then added them using a foreach:

        AlternateView alternateView =  null;
        string body = "";
        string link = @"<a href='http://localhost:55148/Support/Management/Index'>";
        List<LinkedResource> resources = new List<LinkedResource>();
        for (int i = 0; i < images.Count; i++)
        {
            string filepath = images[i];
            LinkedResource res = new LinkedResource(filepath, MediaTypeNames.Image.Jpeg);
            res.ContentId = Guid.NewGuid().ToString();
            body = body + link + @"<img src='cid:" + res.ContentId + @"'/></a>";
            alternateView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
            resources.Add(res);
        }
        foreach(LinkedResource r in resources)
        {
            alternateView.LinkedResources.Add(r);

        }

        return alternateView;