To create an embedded image we will need to first create an
HTML view of the email using AlternateView class. Within that alternate view we
need to create a tag that points to the ContentId (cid) of the LinkedResource
of the image view as shown below.
Listing 1 – Sample for HTML view
// to embed images, we need to use the prefix 'cid' in the img src value
string htmlBody = "<b>This is the embedded image file.</b><DIV> </DIV>";
htmlBody += "<img alt=\"\" hspace=0 src=\"cid:uniqueId\" align=baseline border=0 >";
htmlBody += "<DIV> </DIV><b>This is the end of Mail...</b>";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody,
null, "text/html");
Then we need to create a LinkedResource object and add it to
the AlternateView's LinkedResources Collection. Again, before adding this be
sure to set the ContentId property of LinkedResource class as that unique value
set in the HTML tag of AlternateView (i.e. cid). Here we need to set the
TransferEncoding property of LinkedResource to Base64 which is the default for the
image.
Listing 2 – Sample for Image resource
// create the image resource from image path using LinkedResource class..
LinkedResource imageResource = new LinkedResource("c:\\attachment\\image1.jpg" ,
"image/jpeg");
imageResource.ContentId = "uniqueId";
imageResource.TransferEncoding = TransferEncoding.Base64;
Here "uniqueId" is the common unique cid value.
Let us add the above "imageResource" to "htmlView."
Listing 3 – Sample for adding Image in HTML part
// adding the imaged linked to htmlView...
htmlView.LinkedResources.Add(imageResource);
Then we have to add this htmlView (AlternateView object) to
the MailMessage object.
Listing 4 – Setting the mail message
// add the view
mail.AlternateViews.Add(htmlView);