Click here to Skip to main content
Click here to Skip to main content
Go to top

Embed an Image in Email using ASP.NET

, 21 Dec 2008
Rate this:
Please Sign up or sign in to vote.
Complete demo of embedding images in an email message.

EmbedImage

Introduction

This article presents a complete example of embedding an image in an email message. There are plenty of examples in the Internet; however, they are incomplete.

I spent many hours researching and getting the pieces together, and decided to share the results with my fellow developers.

Background

The code is based on functionality delivered by the .NET Framework (v 2.0, 3.0, and 3.5) which is not very efficient. If you plan to do some heavy emailing, please do not use this code.

The code is in VB, and the example is a one page website using VS 2008. You can copy and paste the code if you are using a previous version of VS.

Using the code

The code is very simple, and can be lifted and incorporated into an application easily. In fact, the basis of the code was used for a project for a client where the recipient's email address is selected from a GridView. (Can't post that one, is work-for-hire!)

Don't forget to update your web.config file! You can add the host and credentials inside the code, but I prefer to use the configuration file. Simply add the following lines to your web.config file:

<system.net>
  <mailSettings>
    <smtp from="user@somehost.com">
     <network host="smtp.somehost.com" password="somepassword" 
       userName="user@somehost.com" port="587" />
    </smtp>
  </mailSettings>
</system.net> 

The port should be 25, but some ISPs prefer that 587 is used. It makes no difference to the application.

Points of interest

With many of the other examples, you get an email with the graphic attached as a .dat file, not at all what is intended.

The missing ingredient is specifying the type of the attachment and its encoding:

Dim imageResourceEs As New _
  System.Net.Mail.LinkedResource(fileImage.PostedFile.FileName, "image/gif")
imageResourceEs.TransferEncoding = Net.Mime.TransferEncoding.Base64

In most other examples, the second parameter is missing when creating the LinkedResource, and they fail to set an encoding for the file; thus it is attached instead of embedded.

Make sure to change the MIME type (image/GIF, image/JPEG, etc.) to match the type of the file you are embedding. The message body is a string formatted with HTML tags. Some renderers will let you do some things while other will balk, your mileage may vary.

The string is the parameter passed to CreateAlternateViewFromString, and as you can see in the example, I use a style to set the font family and size.

htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString("<html><body " & _ 
   "style='font-family:Segoe UI, Arial; font-size: 11pt;'><p>" & _
   txtBody.Text.Trim & "</p>'<img src='cid:image1'></body></html>", Nothing, "text/html")

Basically, what we're doing is creating an "anchor" inside the HTML message with the code img src:'cid imageName' and then defining the resource and linking it so that the HTML renderer can find it.

Another important point is to make sure the name in the img tag in the HTML string is enclosed in quotes (single or double) and that it matches precisely the name of the resource:

img src="cid:image1"
imageResourceEs.ContentId = "image1"

Once you understand that we are using the img tag to allocate the "space" inside the HTML message and linking the resource so it can be found, you will see that adding multiple images is a matter of creating multiple tags and linking multiple resources:

!Inside the HTML message create the "holders" for the images
img src="cid:image1"
img src="cid:image2"

! Create the resources
Dim lkImage1 As New 
 System.Net.Mail.LinkedResource(FileName, "image/gif")

Dim lkImage2 As New 
 System.Net.Mail.LinkedResource(FileName, "image/gif")

! Link the resources
lkImage1.ContentId = "image1"
lkImage2.ContentId = "image2"

The message is displayed correctly in Gmail:

GMail Screenshot

and Outlook:

Outlook Screenshot

I have tested the code with other email engines such as Yahoo! and others, but not Hotmail. It should work, but Hotmail is very quirky when rendering HTML messages.

The code also creates a "text view" incorporating the "body" of the message without the graphic element, so that something is displayed if the email client can't display the HTML version.

Enjoy!

History

  • First version: December 19, 2008.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jelizondo21

Mexico Mexico
I stated with computers before they had a display (just punch-card readers and teletypes for I/O) and learned much along the way.
For many years I was in charge of IT for an international company in the hospitality business before moving on to other ventures.
I now do free-lance IT consulting and programming, both for hire and for assorted charities.

Comments and Discussions

 
Questionimage not found Pinmemberlolybash19-Dec-12 2:25 
QuestionConvert HTML with Images to an imbeded version Pinmemberlance.spurgeon7-Oct-12 21:36 
QuestionThanks!! PinmemberSettt17-Jan-12 21:31 
QuestionImage not found error Pinmemberovaisgeo17-Oct-11 0:25 
Generaldoes it make email heavy PinmemberIMQ26-Sep-10 3:29 
Generalreg embeding images in email Pinmembersvknair10-Jul-10 1:37 
Generalemail bounce PinmemberMember 45455487-Jan-09 13:15 
AnswerRe: email bounce Pinmemberjelizondo217-Jan-09 15:57 
Hello Neil:
 
Thanks for your note.
 
The problem is very undefined; it could be related to a any number of things from your mail server being blacklisted to the recipient having placed your email address in an internal blacklist or policy configuration error in the recipient's server.
 
Without a lot more information I'm unable to help you but I suggest that if your email is legitimate (i.e not unwanted spam) you set the reply-to field:
 
mailMessage.ReplyTo = New System.Net.Mail.MailAddress("yourname@yourcompany.com")
 
some servers use it to detect spam if the reply-to address can't be traced back or is empty.
 
If you are sending unwanted email then the problem complicates because it might be refused by any spam-detecting utility on the recipient's server and bypassing those is beyond my knowledge.
 
Cheers,
 
Jerry
QuestionEmbedded image in iPhone PinmemberSaurabh Shah10-Jun-09 20:58 
Generalthanks for sharing PinmemberMember 45455487-Jan-09 12:47 
AnswerRe: thanks for sharing Pinmemberjelizondo217-Jan-09 13:05 
GeneralYou realy doing great work PinmemberRai Shahid24-Dec-08 21:23 
AnswerRe: You realy doing great work Pinmemberjelizondo217-Jan-09 13:04 
GeneralVery nice article 5 from me. PinmemberAnurag Gandhi24-Dec-08 6:19 
GeneralRe: Very nice article 5 from me. Pinmemberjelizondo2124-Dec-08 8:10 
Questionnice article but 1 question PinmemberKishan Hathiwala24-Dec-08 5:26 
AnswerRe: nice article but 1 question Pinmemberjelizondo2124-Dec-08 6:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 21 Dec 2008
Article Copyright 2008 by jelizondo21
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid