Html电子邮件正文未正确呈现

时间:2017-09-25 09:14:32

标签: c# html css

我正在尝试发送包含身体内嵌图像的电子邮件。我提供了由C#代码生成的html外观的js小提琴。我在js小提琴中使用了更新的src,以便显示图像。 js小提琴可以访问 here

正确发送电子邮件,并将图片嵌入正文中。我的问题是div的样式,当我在outlook中查看时,它们没有对齐。为此,我提供了以下截图:

enter image description here

正如你在屏幕截图中看到的那样,div被堆叠在js小提琴中,它们是对齐的。请问有人告诉我哪里出错了。以下是我的代码。

MailMessage message = new MailMessage();
message.To.Add(new MailAddress("to"));
message.From = new MailAddress("from");
LinkedResource res = new LinkedResource(@"C:\TestFolder\TestImage.jpg");
message.Subject = "Test Email";
message.IsBodyHtml = true;

StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.Append("<body>");
sb.Append("<div style=\"display: flex; justify-content: space-between;\">");
sb.Append("<div style=\"width: auto; height: 100px;\">");
sb.Append("<img style=\"height: 100px;\" src='cid:" + res.ContentId + @"'/>");
sb.Append("</div>");
sb.Append("<div style=\"width: auto; height: 100px;\">");
sb.Append("<h1>Hello World</h1>");
sb.Append("</div>");
sb.Append("<div style=\"width: auto; height: 100px;\">");
sb.Append("<img style=\"height: 100px;\" src='cid:" + res.ContentId + @"'/>");
sb.Append("</div>");
sb.Append("</div>");
sb.Append("</body>");
sb.Append("</html>");

AlternateView alternateView = AlternateView.CreateAlternateViewFromString(sb.ToString(), null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
message.AlternateViews.Add(alternateView);

using (var smtp = new SmtpClient())
{
   var credential = new NetworkCredential
   {
      UserName = "email", 
      Password = "password"
   };
   smtp.Credentials = credential;
   smtp.Host = "host";
   smtp.Port = 587;
   smtp.Send(message);
}

最后,如果我这样做,sb.ToString()会生成以下html字符串。

<div style="display: flex; justify-content: space-between;">
  <div style="width: auto; height: 100px;">
    <img style="height: 100px;" src="http://d3sdoylwcs36el.cloudfront.net/VEN-virtual-enterprise-network-business-opportunities-small-fish_id799929_size485.jpg">
  </div>
  <div style="width: auto; height: 100px;">
    <h1>Hello World</h1>
  </div>
  <div style="width: auto; height: 100px;">
    <img style="height: 100px;" src="http://d3sdoylwcs36el.cloudfront.net/VEN-virtual-enterprise-network-business-opportunities-small-fish_id799929_size485.jpg">
  </div>

1 个答案:

答案 0 :(得分:0)

    

    <div style="width: auto; height: 100px;display:table;width:150px;float:left">
        <img style="height: 100px;" src='http://d3sdoylwcs36el.cloudfront.net/VEN-virtual-enterprise-network-business-opportunities-small-fish_id799929_size485.jpg' />
    </div>
    <div style="width: auto; display:table;width:400px;float:left;text-align:center;">
        <h1>
            Hello World</h1>
    </div>
    <div style="width: auto; height: 100px;display:table;width:150px;float:left;text-align:right;">
        <img style="height: 100px;" src='http://d3sdoylwcs36el.cloudfront.net/VEN-virtual-enterprise-network-business-opportunities-small-fish_id799929_size485.jpg' />
    </div>
</div>