1

This questions has been posed and answered several places on SO, specifically here : Issue with Gmail - Embedded images using MailKit and handles my exact query, yet the answer doesn't seem to work for my case.

I've tried to build a simple mailer that embeds images in an HTML email, yet in several clients, all images still end up as attachments.

I suspect the fault to be in the way I handle the image attachments (one .gif and several .png) to be:

// Add pictures to embedded resources and replace links to pictures in the message
foreach (string imgpath in ImgPaths)
{
    var image = builder.LinkedResources.Add(imgpath);
    image.ContentId = MimeUtils.GenerateMessageId();
    image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
    HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
}
builder.HtmlBody = HtmlFormat;
message.Body = builder.ToMessageBody();

I can see from the emails (received in Gmail, for instance), do show that the images are being listed as:

src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5@Loralei"

All images are attached as attachments in both clients I've tried (gmail and roundcube). I've walked through your tutorials and checked out everything here: https://stackoverflow.com/search?q=Mailkit+Embed Sadly, I just can't seem to find my error. Hopefully @jstedfast could see where I make my mistake?

UPDATE

As mentioned by @jstedfast, the corrected code should be (for my case anyway):

foreach (string imgpath in ImgPaths)
            {
                var test = Path.GetFileName(imgpath);
                var image = builder.LinkedResources.Add(imgpath);
                image.ContentId = MimeUtils.GenerateMessageId();
                image.ContentDisposition = new ContentDisposition() { Disposition = ContentDisposition.Inline };
                //HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));
                HtmlFormat = HtmlFormat.Replace($"images/{test}", string.Format("cid:{0}", image.ContentId)); //use images/filename
            }

This is a great guide to follow too, https://programming.vip/docs/5dac3983f0cd5.html

jps
  • 20,041
  • 15
  • 75
  • 79
Medismal
  • 421
  • 3
  • 18

1 Answers1

1

This looks like the problem:

<img src="images/cid:TPSXHQUDSAU4.JJRKUIEGLTZ5@Loralei" .../>

That needs to be:

<img src="cid:TPSXHQUDSAU4.JJRKUIEGLTZ5@Loralei" .../>

My guess is that in order to fix this, you'd change the following line of code:

HtmlFormat = HtmlFormat.Replace(Path.GetFileName(imgpath), string.Format("cid:{0}", image.ContentId));

to this:

HtmlFormat = HtmlFormat.Replace(imgpath, string.Format("cid:{0}", image.ContentId));

Hope that helps!

jstedfast
  • 35,744
  • 5
  • 97
  • 110