Skip to main content

Email messages with embedded images

Finally stumbled upon the way to create email messages with embedded images in ASP.NET 2.0. (Note that this doesn't work for ASP.NET 1.1, sorry to say.)

For review ... you can add an image to an email message in these ways:

* Attach it. Works ok, but it's ... attached. Illustrated earlier.
* In an HTML-formatted message, create an tag that points to an absolute URL.
* In an HTML-formatted message, create an tag that points to an embedded image and then (duh) embed the image. In that case, the image shows up inline with the message's text.

Pointing to an absolute URL keeps the message size down, but you have no control over the image on the server, and it could go away or change. Attaching and embedding keep a copy of the image with the message, but bloat the message size.

So, embedding. The trick, such as it is, is to create an alternative view and to add a linked resource to the alternative view. Alternative views enable you to create different versions of the email message -- typically one in plain text and the other formatted with HTML. These then substitute for the basic msg.Body property. Behind the scenes, the class creates the appropriately formatted multipart email that incorporates the alternative views, which lets the email client choose which one to use.

To do the actual embedding, you need to do a number of things:

* Create an HTML-formatted message.
* Use an tag in the message body.
* For the src attribute of the , 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 tag.
* Assign the image's file name to the linked resource.

(I think it takes more lines to describe it than to actually do it.)

Here's code. I can't take credit for it. I played with this for a long time trying to get it to work and came close, but I ultimately relied on an example provided by mharder in an internal email. Note the syntax of the tag and the use of ContentId, ContentType.Name, and filename.

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: "


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

Comments

Popular posts from this blog

World Environment Day

This entry is in response to the Conserve, Recycle and Discover contest organised by blogadda.com in association with Pringoo ! World Environment Day, commemorated on 5 June since 1972, is one of the ways focuses world attention on the environment and encourages political action. People from countries all over the world have mobilized for individual and organized environmental action. Activities involve all sectors of society, governments, non- and inter-governmental organizations, businesses, industries, civil society, media and schools. Please take the following Pledge to save our environment. 1, I pledge to Recycle more, use less water and electricity. 2, I pledge to smoke less in 2010. 3, I pledge to send more electronic documents instead of using paper. 4, I pledge to continue using my bicycle to go to work (instead of my motorbike). 5, wash with full loads it is more energy efficient than doing several smaller ones. 6, Incite of dryer I will use hang dry for energy sav...

GridView Alphabet Paging

Introduction: GridView paging feature allow us to display fixed number of records on the page and browse to the next page of records. Although paging is a great feature but sometimes we need to view all the items alphabetically. The idea behind this article is to provide a user with a list of all the alphabets and when the user clicks on a certain alphabet then all the records starting with that alphabet will be populated in the GridView control. Populating the GridView Control: The first task is to populate the GridView control. I will be using the Northwind database in my article which, is installed by default for SQL SERVER 2000 and SQL SERVER 7 databases. The code below is used to populate the GridView control. private void BindData() { string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true"; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter("SELECT P...

TED

TED is a nonprofit devoted to Ideas Worth Spreading. It began in 1984 as an annual conference devoted to Technology, Entertainment and Design -- hence TED -- but TED's reach, and its scope, have become ever broader since then. TEDTalks cover science, arts, politics, global issues, architecture, music and more. Speakers come from a wide variety of communities and disciplines -- people like Bill Clinton, Nobel laureate Murray Gell-Mann, Wikipedia co-founder Jimmy Wales, and Google co-founders Sergey Brin and Larry Page. The TED Conference itself takes place in Long Beach each spring, with a simulcast event in Palm Springs. In 2009, we'll also host a summer conference in Oxford, UK, called TEDGlobal, as well as a conference in fall 2009 called TEDIndia, in Mysore, India. Anyone can apply to attend a TED Conference! If you want to come, apply for an invitation. More info here: http://www.ted.com/conferences