0

我需要使用 C# 在 MailMessage 中连续嵌入 5 个链接,其中包含图像。问题只是电子邮件中显示的最后一个嵌入图像。我需要的结果是这样的:

在此处输入图像描述

以下是已发送电子邮件中显示的内容:

在此处输入图像描述

这是我的代码:

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

1 回答 1

0

我想到了。我不知道为什么会有所不同,但我将 LinkedResources 收集到一个列表中,然后使用 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;
于 2021-03-11T16:46:02.403 回答