Monday, April 14, 2008

Send Email Using (System.Net.Mail)

First create new website project and add two pages :-
SendEmail.aspx and EmailSent.aspx

and in the page SendEmail.aspx add three TextBox (txtFrom , txtSubject , txtMessage)
and add button (Send) and Lable control
and Required Validator for txtFrom , txtSubject and also add CustomValidator control for txtMessage as we want the characters in txtMessage not more than 50 characters



In SendEmail.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 Default2 : System.Web.UI.Page
{
private bool SendMail(string from, string body,string subject)
{
//string mailServerName = "SMTP.ewebbers.com";
string mailServerName = "SMTP.ewebbers.com";
MailMessage message = new MailMessage(from, "y.ahmed@ewebbers.com",subject, body);
SmtpClient mailClient = new SmtpClient();
mailClient.Host = mailServerName;
mailClient.Send(message);
message.Dispose();

return true;
}

protected void Page_Load(object sender, EventArgs e)
{

}

protected void btn_Send_Click(object sender, EventArgs e)
{
bool x=SendMail(txtFrom.Text, txtMessage.Text,txtSubject.Text);
if (x == true)
{
Response.Redirect("~/MailSent.aspx");
}
else
{
Label1.Text = "Try again";
}
}

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txtMessage.Text.Length > 50)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}

}
}


Note:- we can use javascript with CustomValidator to ensure that user not enter more than 50 characters in txtMessage
so we will add Javascript code in SendEmail.aspx page

// function ValidateComments(sender, args)
// {
// if (args.Value.length > 50)
// args.IsValid = false;
// else
// args.IsValid = true;
// }


and in property of CustomValidator control set ClientValidationFunction="ValidateComments"

No comments: