Click here to Skip to main content
Click here to Skip to main content

Embed HTML Email Images

By , 5 Jun 2007
 

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
No Biography provided

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI have an Outlook Integration (without using Exchange)memberPhilip Carter16-Oct-11 6:39 
Generalweb interface html to emlmemberpieruigi12-Oct-10 10:30 
QuestionSSL [modified]memberIvica7619-Sep-10 22:51 
QuestionSPAM problemmemberpinokar2-Jul-07 5:57 
AnswerRe: SPAM problemmembermwdiablo19-Jul-07 12:42 
GeneralYou can also...memberaxelriet5-Jun-07 13:47 
GeneralRe: You can also...membermwdiablo9-Jun-07 16:53 
GeneralAn Easy Way...membermerlin9815-Jun-07 9:14 
GeneralRe: An Easy Way...membermwdiablo19-Jul-07 12:43 
Questionproblem creating NewsLetter....membermohnish.bilimoria31-May-07 22:52 
Generaldon't want to use SmtpServer for sending newslettermemberfarooqahm14-May-07 1:21 
GeneralRe: don't want to use SmtpServer for sending newslettermembermwdiablo20-May-07 22:50 
GeneralimageNodes errormemberSkip6710-Dec-06 6:41 
GeneralRe: imageNodes errormembermwdiablo20-May-07 22:48 
GeneralEmbedd FlashmemberSaarDagan22-Nov-06 3:20 
GeneralRe: Embedd Flashmembermwdiablo20-May-07 22:47 
Generalcodsys.dllmemberjbrathwaite9-Aug-06 18:52 
AnswerRe: codsys.dllmembermwdiablo9-Aug-06 21:55 
Generalhelpmemberbeckymasue1-Aug-06 4:16 
AnswerRe: helpmembermwdiablo1-Aug-06 13:39 
Questionbackground imagesmembertianmingkun23-May-06 0:02 
AnswerRe: background imagesmembermwdiablo4-Jun-06 15:56 
Generalthanksmemberdrkwtkns4-Oct-05 6:47 
GeneralRe: thanksmembermwdiablo4-Oct-05 9:44 
Generaleven birthday to me....memberjreddy26-Sep-05 16:37 
GeneralRe: even birthday to me....membermwdiablo27-Sep-05 0:05 
QuestionPNG?memberThe_Mega_ZZTer26-Sep-05 14:50 
AnswerRe: PNG?membermwdiablo27-Sep-05 0:12 

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

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