Thursday, July 3, 2008

Sending a Web page in an Email using ASP.net

Code to send a web page in an email

private void SendWebPageWithMail()
{
String message = readHtmlPage("http://www.YourWebPageHere.com");

try
{
SendMailMessage("From@YourWebsiteName.com", "To@YourFriend.com",
"bccEmailAddresses",
"ccEmailAddresses",
"Write your Subject Here",
message);
}
catch (Exception ex)
{
// Catch the exception here and do something with it
}
}

///
/// Function used to get the page to be sent
///
///
///
private String readHtmlPage(string url)
{
String result;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}

///
/// Sends an mail message.
/// Code Taken from - http://forums.asp.net/t/971802.aspx
///
/// Sender address
/// Recepient address
/// Bcc recepient
/// Cc recepient
/// Subject of mail message
/// Body of mail message
public static void SendMailMessage(string from, string to, string bcc, string cc, string subject, string body)
{
// Instantiate a new instance of MailMessage
MailMessage mMailMessage = new MailMessage();
// Set the sender address of the mail message
mMailMessage.From = new MailAddress(from);
// Set the recepient address of the mail message
mMailMessage.To.Add(new MailAddress(to));

// Check if the bcc value is null or an empty string
if ((bcc != null) && (bcc != string.Empty))
{
// Set the Bcc address of the mail message
mMailMessage.Bcc.Add(new MailAddress(bcc));
}
// Check if the cc value is null or an empty value
if ((cc != null) && (cc != string.Empty))
{
// Set the CC address of the mail message
mMailMessage.CC.Add(new MailAddress(cc));
} // Set the subject of the mail message
mMailMessage.Subject = subject;
// Set the body of the mail message
mMailMessage.Body = body;

// Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = true;
// Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal;

// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient("www.ServerYouAreSendingTheMailFrom.com");
// Send the mail message
mSmtpClient.Send(mMailMessage);
}

Labels:

Code to get an html page

Got this code online while searching for code to send a webpage in an email using ASP.net
Source - Cant Remember

///
/// Function used to get the page to be sent
///
///
///
private String readHtmlPage(string url)
{
String result;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}

Labels: