Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed an Image Stream to MailMessage

Tags:

c#

stream

email

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);
like image 853
fluf Avatar asked Jun 07 '11 07:06

fluf


2 Answers

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.

like image 89
fluf Avatar answered Nov 14 '22 22:11

fluf


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

After you do the save, you have to "seek" the MemoryStream back to the start.

logo.Position = 0;
like image 23
Jeremy Avatar answered Nov 14 '22 22:11

Jeremy