It's not always clear how to embed (as opposed to attach) an image. The following works for me. The steps are:
- Create an HTML-formatted message.
- Use an <img> tag in the message body.
- For the src attribute of the <img>, point not to a URL, but to a content ID (cid). This points to the portion of the message containing the image stream.
- Create an alternative view.
- Create a linkedResource that slurps up the image you want to embed.
- Assign a content ID to the linked resource -- this should match the cid you used in the <img> tag.
- Assign the image's file name to the linked resource.
Here's some code:
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.IO
[...]
Dim fromAddress As String = "mike@example.com"
Dim toAddress As String = "mike@example.com"
Dim subject As String = "Test EmbeddedImage"
Dim contentId As String = "image1"
Dim path As String = Server.MapPath("~") & "\"
Dim filename As String = path & "MyPicture.jpg"
Dim body As String = "Here is a linked resource: <img src=""cid:image1""/>"
Dim mailMessage As New MailMessage(fromAddress, toAddress)
mailMessage.Subject = "Testing embedded image"
Dim av1 As AlternateView
av1 = AlternateView.CreateAlternateViewFromString(body, Nothing, _
MediaTypeNames.Text.Html)
Dim linkedResource As LinkedResource = New LinkedResource(filename)
linkedResource.ContentId = contentId
linkedResource.ContentType.Name = filename
av1.LinkedResources.Add(linkedResource)
mailMessage.AlternateViews.Add(av1)
mailMessage.IsBodyHtml = True
Dim mailSender As New SmtpClient("smtpHost")
Try
mailSender.Send(mailMessage)
labelStatus.Text = "Message sent!"
Catch ex As Exception
labelStatus.Text = ex.Message
End Try