Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

c# - How to embed an Image Stream to MailMessage

I'm having some difficulty embedding an image from the Properties.Resources to a MailMessage, currently the image does not show in the email i receive.

I have successfully embedded the image from a directory location but would prefer if the image came from memory/the application.

Here is a simplified version of what I am doing.

 Bitmap b = new Bitmap(Properties.Resources.companyLogo);
 MemoryStream logo = new MemoryStream();
 b.Save(logo, ImageFormat.Jpeg);



 MailMessage newEmail = new MailMessage(from, to);
 newEmail.Subject = subject;
 newEmail.IsBodyHtml = true;

 LinkedResource footerImg = new LinkedResource(logo, "image/jpeg");
 footerImg.ContentId = "companyLogo";
 AlternateView foot= AlternateView.CreateAlternateViewFromString(body + "<p> <img src=cid:companyLogo /> </p>", null, "text/html");

 foot.LinkedResources.Add(footerImg);

 newEmail.AlternateViews.Add(foot);             

 SmtpClient server = new SmtpClient(host, port);
 server.Send(newEmail);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok i have solved the problem.

Instead of using the BitMap save method I converted the BitMap to Byte[] and gave the memory stream the Byte[]

Did not work :

 b.Save(logo, ImageFormat.Jpeg);

Did Work:

Bitmap b = new Bitmap(Properties.Resources.companyLogo);
ImageConverter ic = new ImageConverter();
Byte [] ba = (Byte[]) ic.ConvertTo(b,typeof(Byte[]));
MemoryStream logo = new MemoryStream(ba);

I think it has something to do with the Bitmap.Save method, in the MSDN lib it mentioned that the stream has to have an offset of 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...