Embedded Images in HTML Emails with .Net

I had looked for a few examples of how to send embedded images in an html email with the .net api, and the first few I found didn’t work.

This code, found on the blog of one Mike Pope, did work however:

Imports System.Net.Mail
Imports System.Net.Mime
Imports System.IO

Dim fromAddress As String = "mike@elsewhere.com"
Dim toAddress As String = "mike@elsewhere.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

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s