电子邮件中没有嵌入图像

时间:2013-05-09 14:20:09

标签: c# .net email html-email

我尝试发送包含嵌入图片的电子邮件。图像来自List<Bitmap>,我相信它们100%存在。

当我收到电子邮件时,我根本看不到任何图像,HTML看起来像

<img alt="" hspace="0" src="http://image0" align="baseline" border="0">
<br />

<img alt="" hspace="0" src="http://image1" align="baseline" border="0">
<br />

有任何线索吗?

C#就像

var smtp = new SmtpClient();

var msg = new MailMessage(new MailAddress("support@mysite.com", "mysite.com Support"),
                                new MailAddress(email, email));
msg.Subject = "No worries, man";
msg.IsBodyHtml = true;
var bodyBuilder = new StringBuilder();

for (int i = 0; i < pages.Count; i++)
   bodyBuilder.AppendLine(string.Format("<img alt=\"\" hspace='0' src='cid:image{0}' align='baseline' border='0'><br />",i));
var htmlView = AlternateView.CreateAlternateViewFromString(bodyBuilder.ToString(), null, "text/html");

var index = 0;
foreach (var page in pages) // where page is List<Bitmap>
{
   var memoryStream = new MemoryStream();
   page.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

   var imagelink = new LinkedResource(memoryStream, "image/png");
   imagelink.ContentId = string.Format("image{0}", index); 
   imagelink.TransferEncoding = TransferEncoding.Base64;

   htmlView.LinkedResources.Add(imagelink);
   index++;
}

msg.AlternateViews.Add(htmlView);

try
{
    smtp.Send(msg);
    return Json("true", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
   logger.Error(ex.Message, ex);

   return Json("false", JsonRequestBehavior.AllowGet);
}

1 个答案:

答案 0 :(得分:0)

好人

我在这里找到了很棒的解决方案

How to embed an Image Stream to MailMessage

这是正确的代码:

ImageConverter ic = new ImageConverter();
Byte [] ba = (Byte[]) ic.ConvertTo(page,typeof(Byte[]));
var memoryStream = new MemoryStream(ba);
page.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);