Click here to Skip to main content
12,751,832 members (29,788 online)
Click here to Skip to main content
Add your own
alternative version


72 bookmarked
Posted 22 Dec 2006

Sending the contents of a webpage with images as an HTML mail

, 23 Dec 2006
Rate this:
Please Sign up or sign in to vote.
This article shows how you can embed images from a web server into your mail message.


Some time ago, I had written an ASP.NET website showing some reports generated from a database. The reports contained tables, as well as dynamically generated graphs. To get a larger number of people to read the reports, it seemed like a good idea to send them as a weekly email newsletter. To be able to re-read the newsletter in a later stage, it was necessary to include the images, since they are changing over time. Embedding the images makes it also possible to send the mail to people that do not have access to the website.

This article shows a way to retrieve images from a web server and embed them into your email message.


This is how you can send a web page with the mailer class provided in this article:

// The contents that will be sent
Uri uri = new Uri("");

// Configuration of the email message
Fmd.Mail.WebpageMailer mailer = new Fmd.Mail.WebpageMailer();
mailer.SmtpServerName = "";
mailer.Delay = 0;
mailer.MailMessage.From = new MailAddress("");
mailer.MailMessage.To.Add(new MailAddress(""));
mailer.MailMessage.Subject = "Automatic Mail Message " + 
mailer.MailMessage.Priority = MailPriority.Normal;

// Sending the webpage

The main methods of the class

Sending the mail message

SendMailMessage is the main method in the class. It retrieves the contents of the web page to be sent. Next, it retrieves the images to embed. These parts are inserted into a mail message which is sent in the end.

public void SendMailMessage(Uri uri)
    // Retrieve the contents
    string htmlbody = GetBody(uri);
    // See what images there are to embed
    string modifiedbody;            
    List<linkedResource> foundResources;
    ExtractLinkedResources(uri, htmlbody, out modifiedbody, 
                           out foundResources);
    // Write the html to a memory stream
    MemoryStream stream = new MemoryStream();
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(modifiedbody);
    stream.Write(bytes, 0, bytes.Length);            
    stream.Position = 0;

    // Configure the mail so it contains the html page
    _mailMessage.Body = "This is a html mail - use an" + 
                        " email client that can read it";
    AlternateView altView = new AlternateView(stream, 

    // Embed the images into the mail
    foreach (LinkedResource linkedResource in foundResources)
    // Send the mail
    SmtpClient client = new SmtpClient(_smptServerName);

Filling the LinkedResource

This code snippet from ExtractLinkedResources shows how the images are embedded:

// Fill the linked resource
LinkedResource data = new LinkedResource(imageStream);

// Determine a name and set the media type of the linked resource
string generatedName = null;
if (contentType.ToLower().IndexOf("image/gif") >= 0)
    data.ContentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Gif;
    generatedName = "image" + imageID.ToString() + ".gif";
else if (contentType.ToLower().IndexOf("image/jpeg") >= 0)
    data.ContentType.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
    generatedName = "image" + imageID.ToString() + ".jpeg";

// it is something that I don't handle yet
if (generatedName == null)

// Generate the linked resource for the image being embedded
string generatedSrc = "cid:" + generatedName;
data.ContentType.Name = generatedName;
data.ContentId = generatedName;
data.ContentLink = new Uri(generatedSrc);

Getting a web page

This downloads the HTML contents:

public static string GetBody(Uri uri)
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    // Set some reasonable limits on resources used by this request
    request.MaximumAutomaticRedirections = 4;
    request.MaximumResponseHeadersLength = 4;
    // Set credentials to use for this request.
    request.Credentials = CredentialCache.DefaultCredentials;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // Get the stream associated with the response.
    Stream receiveStream = response.GetResponseStream();

    // Pipes the stream to a higher level stream reader
    // with the required encoding format. 
    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

    string body = readStream.ReadToEnd();

    return body;

Glueing everything together

To make everything work together, there are a few things that need to be tackled. Since the images may be in some virtual directory on the web server, different from the page itself, their relative paths need to be changed. The program follows these steps to get everything together:

  1. Read the HTML body
  2. Analyze the HTML body to extract what images need to be retrieved
  3. Download the images, and make them available as a MemoryStream to embed into the mail message
  4. Modify the HTML so the image URLs are relative to the mail message instead of being relative to the web page
  5. Put everything into the mail message and send it away

Final remarks

This article can do two things for you. It can get you started when you want to send web pages as an email message, and the sample code may help you when you are struggling on how to embed images into a mail message. I hope you find it useful!


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

Five Minute Developer
Team Leader
Netherlands Netherlands
My education was Mathematics (with a statistics final). I was one of the six teammembers of the dutch IMO team in 93.

Since 97 I have been working as developer of software for professional traders. In the beginning of my carreer I used mainly C++ and MFC, later on C# began playing a more significant role.

In the last years, I have gotten more management responsabilities, which also increased my interest in teaching computer science to junior developers.

You may also be interested in...

Comments and Discussions

QuestionRegarding the code downloaded Pin
Chetna Khandelwal4-Jun-15 3:36
memberChetna Khandelwal4-Jun-15 3:36 
QuestionHelp for developing Asp.Net site Pin
Member 111948301-Nov-14 3:56
memberMember 111948301-Nov-14 3:56 
Questionautomatic content attachment Pin
Abhishek Jaiswall25-Aug-14 21:32
memberAbhishek Jaiswall25-Aug-14 21:32 
GeneralMy vote of 5 Pin
Nil Castillo19-Mar-12 23:41
memberNil Castillo19-Mar-12 23:41 
GeneralOperation Time Out Pin
sanjay121231-Jul-11 22:30
membersanjay121231-Jul-11 22:30 
GeneralMy vote of 5 Pin
jpleroux383-Apr-11 23:38
memberjpleroux383-Apr-11 23:38 
GeneralOutlook 2007 and 2010 Pin
Ivica7616-Sep-10 22:32
memberIvica7616-Sep-10 22:32 
GeneralHTML email template Pin
Ivica762-Jul-10 10:57
memberIvica762-Jul-10 10:57 
GeneralGmail and Yahoomail do not receive email sent through SYSTEM.NET.MAIL Pin
Zu Luong21-Mar-10 8:40
memberZu Luong21-Mar-10 8:40 
GeneralBackground-image cannot be displayed when I use css to control the url of background-image Pin
shuangking77718-Feb-09 19:42
membershuangking77718-Feb-09 19:42 
GeneralRe: Background-image cannot be displayed when I use css to control the url of background-image Pin
hustyang17-Jun-13 17:54
memberhustyang17-Jun-13 17:54 
GeneralLocalize mail Pin
sayyid.senux13-Feb-09 22:09
membersayyid.senux13-Feb-09 22:09 
GeneralRe: Localize mail Pin
tracky1-May-09 2:41
membertracky1-May-09 2:41 
GeneralRe: Localize mail Pin
tracky1-May-09 3:02
membertracky1-May-09 3:02 
GeneralThanks Pin
herotayson22-Aug-08 1:27
memberherotayson22-Aug-08 1:27 
GeneralCool Good Work Pin
jignesh_login3-Jul-08 22:59
memberjignesh_login3-Jul-08 22:59 
GeneralModify version. Support SMTP Authentication Pin
Cool Dirty Boy27-Oct-07 22:14
memberCool Dirty Boy27-Oct-07 22:14 
GeneralUse of file:// protocol. Pin
rrodriguez3-Aug-07 3:11
memberrrodriguez3-Aug-07 3:11 
GeneralRe: Use of file:// protocol. Pin
Five Minute Developer4-Aug-07 8:29
memberFive Minute Developer4-Aug-07 8:29 
QuestionGet images from a SQL table Pin
sma16241-Mar-07 12:22
membersma16241-Mar-07 12:22 
Generalwant to help Pin
tariq developer24-Jan-07 21:44
membertariq developer24-Jan-07 21:44 
AnswerRe: want to help Pin
Five Minute Developer29-Jan-07 1:17
memberFive Minute Developer29-Jan-07 1:17 
QuestionHow to save/edit the email Pin
LittleGrass22-Jan-07 17:18
memberLittleGrass22-Jan-07 17:18 
AnswerRe: How to save/edit the email Pin
Five Minute Developer23-Jan-07 3:33
memberFive Minute Developer23-Jan-07 3:33 
QuestionHow can it have SMTP basic athentication? Pin
cornejoserrano5-Jan-07 2:22
membercornejoserrano5-Jan-07 2:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web01 | 2.8.170217.1 | Last Updated 23 Dec 2006
Article Copyright 2006 by Five Minute Developer
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid