0

I'm using the following code (C#) to embed an image into an html email:

Bitmap image = new Bitmap();
// set something to image
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
ContentType contentType = new ContentType(MediaTypeNames.Image.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
Attachment attachment = new Attachment(ms, contentType);
attachment.ContentId = "image@email";

MailMessage mail = new MailMessage();
mail.From = new MailAddress("...");
mail.To.Add("...");
mail.Subject = "...";
mail.Body = body; // view below
mail.IsBodyHtml = true;
mail.Attachments.Add(attachment);
smtpClient.Send(mail);
ms.Close();

here the relevant part of the html body:

<img align='center' alt='' src='cid:image@email' width='100' style='padding-bottom: 0; display: inline !important; vertical-align: bottom;'>";            

Viewing the email on the gmail website it looks correct: i.e. the image is embedded into the html body.

Instead, using Thunderbird the image is received as an attachment, but not recognized as jpg. The attachment is named "Part 1.2". If I double click on it the image is opened with the default image viewer installed on the computer.

What I need to add in order to correctly send embedded images in a way that is compatible with the most common email readers?

UPDATE

To name the attached image is enough to add the following:

attachment.Name = "name.jpg";

Still Thunderbird refuses to show it inside the html.

Mark
  • 4,338
  • 7
  • 58
  • 120

1 Answers1

1

As Scarnet pointed out, this is the right way to place an embedded image into an html email:

AlternateView view = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource(filename, MediaTypeNames.Image.Jpeg);
inline.ContentId = "image@email";
view.LinkedResources.Add(inline);

MailMessage mail = new MailMessage();
mail.From = new MailAddress(username);
mail.To.Add(address);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.AlternateViews.Add(view);
await smtpClient.SendMailAsync(mail);
Mark
  • 4,338
  • 7
  • 58
  • 120