Search code examples
c#htmlimagemimekit

c# Sending Email with Mailkit with an HTML template file that has images imbedded


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


Solution

  • 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!