These few lines will allow you to email as html an aspx page from your site or in fact any web page you want (though i wouldnt recommend any with lots of scripts etc in it). It is very useful for email forms to customers etc from your site.
Personally I create an plainer version of the form just for email. I remove any menu functions and other things that are there as part of the website and are not useful in the email - but that is a personal preference.
I have also created an emailer class which i have simplified here for you
using System.Net.Mail;
public static class Emailer
{
public static void SendEmail(string from, string to, string subject, sting body)
{
SmtpClient smtp = new SmtpClient("hostname");
MailMessage email = new MailMessage(from, to, subject, body);
email.IsBodyHtml = true;
smtp.Send(email);
}
}
Now to send the page. Remember it can be any page and so you can do any codebehind processing first that you wish. In essence we call Server.Execute which runs the page as if it were in a browser, but without opening the page in the browser for the user to see. The lines of code are simple as follows:
using System.Net;
using System.IO;
////*** somewhere in an aspx page - preferably a different one to the one you are emailing but doesnt have to be******
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Server.Execute("theaspxpage.aspx", htw);
//the page has now processed and the markup is in the textwriter inner text which is the stringwriter
//I also set a status in the called aspx page and check to see all was ok before continuing but will keep it simple here
Emailer.SendEmail("from@here.com", "to@there.com", "Your aspx page", sw.ToString());
You could pass parameters in the header of server.execute if needed or anything just as calling a normal aspx page. It you wanted to call a third party page instead then you cant use Response.Redirect as that will send the browser to the page. You can use the HttpWebRequest to do it for you. I wont go into that in this tutorial - maybe another day.
Remember if you want to place the code above into the page you want to email then do not put it in the page load without some form of checking (say a flag) otherwise you will go into an neverending loop and overflow error.