Chitika

Friday, September 28, 2012

Sending Web Page as Email

Sending Email in .net in one of the common task we have.
Instead of preparing Email body , if we can can pass complete page data as body then it will be easy to accomplish out task. 
In this example you will see how to send Email in .net with full page data.

Take 4 Textbox control
1 - For URL typing (URL of webpage you want to send as a mail).
2 - For To Field (Email address of user sending the page.)
3 - For From Field (Destination Email address you want to send).
4 - For Subject Line

Now, switch to code view and add following namespace.

using System.IO;
using System.Net;
using System.Web.Mail;



//Function which convert URL information as string
//Which is used latter to passed as body message.
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;
}



//Code for sending webpage as email.
private void btnSend_Click(object sender, System.EventArgs e)
{

//URL is converted into string message.
String message=readHtmlPage(txtURL.Text);
String mailServer = "192.168.0.10"; //Change with your mail server address.
try
{
MailMessage Mailer = new MailMessage();
Mailer.From = txtFrom.Text;
Mailer.To = txtTo.Text;
Mailer.Subject = txtSubject.Text;
Mailer.Body = message;
Mailer.BodyFormat = System.Web.Mail.MailFormat.Html;
SmtpMail.Server(mailServer);
SmtpMail.Send(Mailer);
lblResult.Text = "Page successfully sent!";
}
catch(Exception ex)
{
lblResult.Text = "An error occurred: " + ex.ToString();
}
}




No comments:

Post a Comment