Click here to Skip to main content
Licence 
First Posted 26 Sep 2005
Views 163,500
Downloads 718
Bookmarked 81 times

Embed HTML Email Images

By | 5 Jun 2007 | Article
How to embed images in your email newsletter.

Other projects you will need to download

Screenshot - PSH_Ne2.png

Introduction

How to embed images into an email; short and sweet, but this is all this does.

Background

My sister wanted to send out an email newsletter and wanted to embed images. So, she asked a friend and they sent her some classic ASP code. Then she asked me to make it work. Yeah, right! I fired up VS 2003 and got a hold of MIL HTML Parser and DotNetOpenMail. Within an hour, I had a small little app that could take a webpage, add all the needed images, and change the img tags to point to the content IDs of the images attached to the email and send it off to an email address.

Using the code

This code is really straightforward. Just select an HTML file that you have created, add a subject, a "from" email address, a "to" email address and the SMTP server name or IP address, and then click Send. But what does the code do? Well, you can't get much simpler than this. The code goes off and gets all the img elements.

    // Get All the img nodes
    GetImageNodes(document.Nodes);
    private void GetImageNodes(HtmlNodeCollection nodes)
    {
        foreach (HtmlNode node in nodes)
        {
            HtmlElement element = node as HtmlElement;
            if (element != null)
            {
                if (element.Name.ToLower() == "img")
                {
                    imageNodes.Add(element);
                }
                if (element.Nodes.Count > 0)
                {
                    GetImageNodes(element.Nodes);
                }
            }
        }
    }

Then all the needed images are attached and the src attributes of the img elements are set to the content ID of the attached images.

    // Change all the img nodes
    foreach (HtmlElement element in imageNodes)
    {
        FileInfo imageFileInfo = new FileInfo(Path.Combine(
            fileInfo.DirectoryName, 
            element.Attributes["src"].Value));
        string contentId = 
            imageFileInfo.Name.Replace(imageFileInfo.Extension, 
            string.Empty);

        if (!images.ContainsKey(element.Attributes["src"].Value))
        {
            // Add Image to the Email
            images.Add(
                element.Attributes["src"].Value, imageFileInfo.FullName);
            FileAttachment relatedFileAttachment = 
                           new FileAttachment(imageFileInfo, contentId);
            if ((imageFileInfo.Extension == ".jpg") || 
                (imageFileInfo.Extension == ".jpeg"))
            {
                relatedFileAttachment.ContentType = "image/jpeg";
            }
            else if (imageFileInfo.Extension == ".gif")
            {
                relatedFileAttachment.ContentType = "image/gif";
            }
            emailMessage.AddRelatedAttachment(relatedFileAttachment);
        }

        //Change the src to "cid:<CONTENTID>"
        element.Attributes["src"].Value = string.Format("cid:{0}", contentId);

    }

And then the changed HTML is added to the email message and sent off.

    // set the email text to the changes html
    emailMessage.HtmlPart = new HtmlAttachment(document.HTML);

    emailMessage.Send(new SmtpServer(this.SmtpServerTextBox.Text));

Points of interest

I just slapped this code together in an hour. In fact, writing the article added another 30 minutes. So, this is not code to look to for best practices. I just wanted to embed images into an email with a minimum of hassle and I achieved that goal with this. I hope others will find it useful.

History

  • 5/6/2007 - Version 2.0
  • 27/9/2005 - Version 1.0 - Also happens to be my birthday! :D

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

mwdiablo

Other
Grosvenor Financial Services Group Ltd.
New Zealand New Zealand

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionI have an Outlook Integration (without using Exchange) PinmemberPhilip Carter6:39 16 Oct '11  
Generalweb interface html to eml Pinmemberpieruigi10:30 12 Oct '10  
QuestionSSL [modified] PinmemberIvica7622:51 19 Sep '10  
QuestionSPAM problem Pinmemberpinokar5:57 2 Jul '07  
AnswerRe: SPAM problem Pinmembermwdiablo12:42 19 Jul '07  
GeneralYou can also... Pinmemberaxelriet13:47 5 Jun '07  
GeneralRe: You can also... Pinmembermwdiablo16:53 9 Jun '07  
GeneralAn Easy Way... Pinmembermerlin9819:14 5 Jun '07  
GeneralRe: An Easy Way... Pinmembermwdiablo12:43 19 Jul '07  
Questionproblem creating NewsLetter.... Pinmembermohnish.bilimoria22:52 31 May '07  
Generaldon't want to use SmtpServer for sending newsletter Pinmemberfarooqahm1:21 14 May '07  
GeneralRe: don't want to use SmtpServer for sending newsletter Pinmembermwdiablo22:50 20 May '07  
GeneralimageNodes error PinmemberSkip676:41 10 Dec '06  
GeneralRe: imageNodes error Pinmembermwdiablo22:48 20 May '07  
GeneralEmbedd Flash PinmemberSaarDagan3:20 22 Nov '06  
GeneralRe: Embedd Flash Pinmembermwdiablo22:47 20 May '07  
Generalcodsys.dll Pinmemberjbrathwaite18:52 9 Aug '06  
AnswerRe: codsys.dll Pinmembermwdiablo21:55 9 Aug '06  
Generalhelp Pinmemberbeckymasue4:16 1 Aug '06  
AnswerRe: help Pinmembermwdiablo13:39 1 Aug '06  
Questionbackground images Pinmembertianmingkun0:02 23 May '06  
AnswerRe: background images Pinmembermwdiablo15:56 4 Jun '06  
Generalthanks Pinmemberdrkwtkns6:47 4 Oct '05  
GeneralRe: thanks Pinmembermwdiablo9:44 4 Oct '05  
Confused | :confused:
That is not the point, you can do that with any html enabled email application like outlook.
With this you do not get the anoying image placeholders when you open the email in outlook (which is a security feature) the images show immediately. And if you optimize your images the email should not be more than a couple of 100KB in the one I did for my sister the email was only 253KB big (and she used very high res pictures to start with) and with 56Kbs being the entry level modems these days that is not very big.
 
In anycase this is a choice you make when sending out your newsletter or email, if your audience has slow connections in general then don't use this method otherwise if they have fast connections then this is an option, but then again you need to look at the size of your images and the size of the email as well and make your dicision.
 
So thanks for the feedback and keep it coming.
Generaleven birthday to me.... Pinmemberjreddy16:37 26 Sep '05  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 5 Jun 2007
Article Copyright 2005 by mwdiablo
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid