Monday, August 07, 2006

How to send a mail from the ASP.NET web form.



In .NET 2.0 we have SmtpClient class that allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
Namespace: System.Net.Mail

Example
protected void BtnSubmit_Click(object sender, EventArgs e)
{
if(!validateFields())
return;


SmtpClient smtpClient = new SmtpClient(host, port);
smtpClient.Credentials = new NetworkCredential(user, password);

MailAddress from = new MailAddress(EmailBox.Text, NameBox.Text);
MailAddress to = new MailAddress(to_mail);

MailMessage message = new MailMessage(from, to);
message.Subject = string.Format(subject_template, NameBox.Text, PhoneBox.Text);
message.Body = QuestionBox.Text;
try
{
smtpClient.Send(message);
Response.Redirect(redirect_success,true);
}
catch(Exception ex)
{
ErrorMessage = ex.Message;
Response.Redirect(redirect_error, true);
}
}

LandVP LLC