5,696,038 members and growing! (12,123 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Email     Intermediate

Embed HTML Email Images

By mwdiablo

How to embed images in your email newsletter.
C#, Windows, .NET 1.1, .NET, WinForms, Visual Studio, VS.NET2003, Dev

Posted: 26 Sep 2005
Updated: 5 Jun 2007
Views: 82,184
Bookmarked: 61 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
9 votes for this Article.
Popularity: 4.47 Rating: 4.68 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 11.1%
3
1 vote, 11.1%
4
7 votes, 77.8%
5

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



Occupation: Team Leader
Company: Intergen
Location: New Zealand New Zealand

Other popular Internet / Network articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
QuestionSPAM problemmemberpinokar6:57 2 Jul '07  
AnswerRe: SPAM problemmembermwdiablo13:42 19 Jul '07  
GeneralYou can also...memberaxelriet14:47 5 Jun '07  
GeneralRe: You can also...membermwdiablo17:53 9 Jun '07  
GeneralAn Easy Way...membermerlin98110:14 5 Jun '07  
GeneralRe: An Easy Way...membermwdiablo13:43 19 Jul '07  
Questionproblem creating NewsLetter....membermohnish.bilimoria23:52 31 May '07  
Generaldon't want to use SmtpServer for sending newslettermemberfarooqahm2:21 14 May '07  
GeneralRe: don't want to use SmtpServer for sending newslettermembermwdiablo23:50 20 May '07  
GeneralimageNodes errormemberSkip677:41 10 Dec '06  
GeneralRe: imageNodes errormembermwdiablo23:48 20 May '07  
GeneralEmbedd FlashmemberSaarDagan4:20 22 Nov '06  
GeneralRe: Embedd Flashmembermwdiablo23:47 20 May '07  
Generalcodsys.dllmemberjbrathwaite19:52 9 Aug '06  
AnswerRe: codsys.dllmembermwdiablo22:55 9 Aug '06  
Generalhelpmemberbeckymasue5:16 1 Aug '06  
AnswerRe: helpmembermwdiablo14:39 1 Aug '06  
Questionbackground imagesmembertianmingkun1:02 23 May '06  
AnswerRe: background imagesmembermwdiablo16:56 4 Jun '06  
Generalthanksmemberdrkwtkns7:47 4 Oct '05  
GeneralRe: thanksmembermwdiablo10:44 4 Oct '05  
Generaleven birthday to me....memberjreddy17:37 26 Sep '05  
GeneralRe: even birthday to me....membermwdiablo1:05 27 Sep '05  
GeneralPNG?memberThe_Mega_ZZTer15:50 26 Sep '05  
GeneralRe: PNG?membermwdiablo1:12 27 Sep '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Jun 2007
Editor: Genevieve Sovereign
Copyright 2005 by mwdiablo
Everything else Copyright © CodeProject, 1999-2008
Web13 | Advertise on the Code Project