简体   繁体   中英

Embedding Multiple Images in Email Displays only Last Image C#

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:

在此处输入图像描述

Here is what displays in the delivered email:

在此处输入图像描述

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM