通过电子邮件发送HTML文档,使用c#嵌入图像

Mar*_*ier 4 html c#

所以这是我的情况.

我需要以HTML格式发送电子邮件,其中嵌入了图像.我尝试将我的图像转换为base64,但它不起作用.

该电子邮件有3个图像,类型为System.Drawing.Image.我只需要在我的html格式化字符串中获取它们.

小智 40

在使用时将图像嵌入电子邮件的另一种方法System.Net.Mail是将图像从本地驱动器附加到电子邮件并分配contentID给它,然后contentID在图像URL中使用它.

这可以这样做:

msg.IsBodyHtml = true;
Attachment inlineLogo = new Attachment(@"C:\Desktop\Image.jpg");
msg.Attachments.Add(inlineLogo);
string contentID = "Image";
inlineLogo.ContentId = contentID;

//To make the image display as inline and not as attachment

inlineLogo.ContentDisposition.Inline = true;
inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline;

//To embed image in email

msg.Body = "<htm><body> <img src=\"cid:" + contentID + "\"> </body></html>";
Run Code Online (Sandbox Code Playgroud)

  • +1非常好的解决方案.我现在可以在余下的时间里做点别的事了.;) (2认同)

小智 2

您关于转换为 Base64 的说法是正确的,但嵌入它还不够(客户端无法区分 Base64 与纯文本),您需要对其进行一些格式化。

查看 Buhake 的答案,它很好地涵盖了一般问题(您应该能够从那里获取它): How to embed images in email