Monday, April 27, 2009

How 2 send mail using asp.net?

ASP.NET Email Tutorial
This tutorial will show you how to send a simple email message using ASP.NET 2.0 and C#
Sending a email using ASP.NET 2.0 and C# 2.0 is actually very simple. First, you will need to import the System.Net.Mail namespace.The System.Net.Mail namespace contains the SmtpClient and MailMessage Classes that we need in order to send the email.
using System.Net.Mail; // Importent
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!We use the btnSubmit_Click event to do the work.We then call the emailClient.Send to send the message using the variables from our ASP.NET coded page.
protected void btnSubmit_Click(object sender, EventArgs e){
try{
MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);emailClient.Send(message);litStatus.Text = "Message Sent";}catch (Exception ex){
litStatus.Text=ex.ToString();}}
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
The front end .aspx page looks something like this:
To
From
SMTP Server
Subject
Body
Action
Status

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
The flow for the code behind page is as follows.
using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Net.Mail;public partial class _Default : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){}protected void btnSubmit_Click(object sender, EventArgs e){
try{
MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);emailClient.Send(message);litStatus.Text = "Message Sent";}catch (Exception ex){
litStatus.Text=ex.ToString();}}}


It is not possible to change SMTPServer (in codebehind ) hence change in web.config :

in code behind :
add String str = ConfigurationManager.AppSetting("SMTPServer");

No comments:

Post a Comment