<<Back To Faq 4.8


Complete FAQ Listing


4.8 How do I send a web page? Printer Friendly

System.Net.Mail does not natively support sending a web page. However, using the WebRequest class, you can screen scrape web pages, and pass the resulting Html string to the MailMessage object. The following example demonstrates this technique.

Note: Be sure to import the System.Net and System.IO namespaces for this code snippet.

[ C# ]

public static void EmailWebPage()
        {
            //create the mail message
            MailMessage mail = new MailMessage();

            //set the addresses
            mail.From = new MailAddress("me@mycompany.com");
            mail.To.Add("you@yourcompany.com");

            //set the content
            mail.Subject = "This is an email";

            //screen scrape the html
            string html = ScreenScrapeHtml("http://localhost/example.htm");
            mail.Body = html;
            mail.IsBodyHtml = true;

            //send the message
            SmtpClient smtp = new SmtpClient("127.0.0.1");
            smtp.Send(mail);

        }
        public static string ScreenScrapeHtml(string url)
        {
            WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
            StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
            string result = sr.ReadToEnd();
            sr.Close();
            return result;
        }


[ VB.NET ]
    Public Sub EmailWebPage()
        'create the mail message
        Dim mail As New MailMessage()

        'set the addresses
        mail.From = New MailAddress("me@mycompany.com")
        mail.To.Add("you@yourcompany.com")

        'set the content
        mail.Subject = "This is an email"

        'screen scrape the html
        Dim html As String = ScreenScrapeHtml("http://localhost/example.htm")
        mail.Body = html
        mail.IsBodyHtml = True

        'send the message
        Dim smtp As New SmtpClient("127.0.0.1")
        smtp.Send(mail)
    End Sub 'EmailWebPage

    Public Function ScreenScrapeHtml(ByVal url As String) As String
        Dim objRequest As WebRequest = System.Net.HttpWebRequest.Create(url)
        Dim sr As New StreamReader(objRequest.GetResponse().GetResponseStream())
        Dim result As String = sr.ReadToEnd()
        sr.Close()
        Return result
    End Function 'ScreenScrapeHtml




 



The formatted version of this faq can be found at http://www.SystemNetMail.com/faq/4.8.aspx