Embedding images is something that is new with
System.Net.Mail in .NET Framework 2.0. To embed an image we will need to:
·
Create an AlternateView object for the Image. The AlternateView
will actually contain the binary data of the Image. This binary data is encoded
as part of the email and sent along as part of the MailMessage.
·
Set the ContentId property of AlternateView Class to a unique
value.
·
Create a HTML AlternateView.
·
Inside that HTML text, we need to use the standard <img>
tag.
·
For the "src" value, we need to point it at the Content-Id
of the AlternateView image. This is done by using the syntax <img
src="cid:ContentId value">. The "src=cid:" part is
required for the email client to recognize the <img> tag as an embedded
image, while the "ContentId value" part is the actual Content-Id of
the AlternateView image.
That is all there is to create an embedded image view. Below
is a short but complete example that demonstrates creating an embedded image
message.
Listing 9 – Sample of an Html mail with embedded
image
Public Sub EmbeddedImages()
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("from@fromdomain.com", " Display Name")
mail.To.Add("to@todomain.com")
'set the content
mail.Subject = "This is an embedded image mail"
'first we create the Plain Text part
Dim palinBody As String = "This is my plain text content, viewable by
those clients that don't support html"
Dim plainView As AlternateView =
AlternateView.CreateAlternateViewFromString(palinBody, Nothing,
"text/plain")
'then we create the Html part
'to embed images, we need to use the prefix 'cid' in the img src value
Dim htmlBody As String = "<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>"
Dim htmlView As AlternateView =
AlternateView.CreateAlternateViewFromString(htmlBody, Nothing,
"text/html")
'create the AlternateView for embedded image
Dim imageView As New AlternateView("c:\attachment\image1.jpg",
MediaTypeNames.Image.Jpeg)
imageView.ContentId = "uniqueId"
imageView.TransferEncoding = TransferEncoding.Base64
'add the views
mail.AlternateViews.Add(plainView)
mail.AlternateViews.Add(htmlView)
mail.AlternateViews.Add(imageView)
'send mail
SendMail(mail)
End Sub ' End EmbedImages
"ImageView" is the instance of AlternateView
created using the constructor which takes two parameters as: fileName (with
path of image) as String, and mediaType as String. Here we use the public
string type constant "Jpeg" of MediaTypeNames.Image Class, which is
actually “image/jpeg."
Again, the "TransferEncoding" property of
"imageView" (AlternateView Class) is set to "Base64."