3

I would like to send an email using MailKit by linking to an html template that has images imbedded, for the C# part I use this code :

var email = new MimeMessage();
var bodyBuilder = new BodyBuilder();
var image= bodyBuilder
    .LinkedResources
    .Add(@"E:\Hicham\MIMNESTHelper\image.jpg");

image.ContentId = MimeUtils.GenerateMessageId();

using (StreamReader SourceReader = System.IO.File.OpenText("E:\\Hicham\\MIMNESTHelper\\EmailTemplate.html"))
{               
    bodyBuilder.HtmlBody =  SourceReader.ReadToEnd();
}
            
email.Body = bodyBuilder.ToMessageBody();

In my html template body, I have tried to add the cid to the attached image as such:

<div style="background-color:#000000;padding:1em;width:50%">
    <center><img src='image.ContentId' /></center>
</div>

thanks

Hicham

Ivan Gechev
  • 706
  • 3
  • 9
  • 21
Hitchb
  • 33
  • 3
  • Should should explain how inline images work in emails: https://blog.elmah.io/how-to-send-emails-from-csharp-net-the-definitive-tutorial/#inline-images – ThomasArdal Oct 26 '22 at 10:23

1 Answers1

2

I suggest that your html file have a placeholder that you can replace later.

<img src='cid:[img-src]' />

And in your code, replace the placeholder with the correct value:

bodyBuilder.HtmlBody = bodyBuilder.HtmlBody.Replace("[img-src]", image.ContentId);

email.Body = bodyBuilder.ToMessageBody();

Goodluck!

rjs123431
  • 688
  • 4
  • 14