Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MimeKit: How to embed images?

Tags:

c#

mimekit

I am using MailKit/MimeKit 1.2.7 (latest NuGet version).

I tried to embed an image in the HTML body of my email by following the sample from the API documentation (section "Using a BodyBuilder").

My current code looks like this:

 var builder = new BodyBuilder();

 builder.HtmlBody = @"<p>Hey!</p><img src=""Image.png"">";

 var pathImage = Path.Combine(Misc.GetPathOfExecutingAssembly(), "Image.png");
 builder.LinkedResources.Add(pathLogoFile);
 message.Body = builder.ToMessageBody();

I can send this email and in fact the image is attached to the email. But it is not embedded.

Am I missing something? Or is this Apple Mail's fault (this is the email client I am using for receiving emails)?

I am grateful for any idea (and thanks so much to Jeffrey Stedfast for providing such a great toolset!!).

Ingmar

like image 289
Ingmar Avatar asked Jul 14 '15 12:07

Ingmar


2 Answers

Try something a bit more like this:

var builder = new BodyBuilder ();
var pathImage = Path.Combine (Misc.GetPathOfExecutingAssembly (), "Image.png");
var image = builder.LinkedResources.Add (pathLogoFile);

image.ContentId = MimeUtils.GenerateMessageId ();

builder.HtmlBody = string.Format (@"<p>Hey!</p><img src=""cid:{0}"">", image.ContentId);

message.Body = builder.ToMessageBody ();

If this works for you, I'll update the documentation.

The problem might be that Apple's multipart/related implementation does not resolve the Image.png reference using the Content-Location header on the image mime part (possibly because it is a relative URL).

The cid: URL-type should work, though, but it's a bit more awkward to construct since you need to know the Content-Id values for each image attachment.

like image 182
jstedfast Avatar answered Nov 14 '22 21:11

jstedfast


Just for reference, this can be found under http://www.mimekit.net/docs/html/Creating-Messages.htm now. The link in the original answer is broken.

like image 38
FranzHuber23 Avatar answered Nov 14 '22 22:11

FranzHuber23