Wednesday, September 17, 2008

Send email with System.Net.Mail in ASP.net 2.0

Send email from ASP.net 2.0:
This function use for sending email from your asp.net 2.0 application.

C# code:
public void Send_Email(string stremailTo, string strContent, string strSubject)
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
// System.Net.Mail.SmtpClient is the alternate class for this in 2.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
try
{
//change your from email id
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("Fromemailid");
//write you smtp address
smtpClient.Host = "localhost";
//Default port will be 25
//smtpClient.Port = 25;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(stremailTo);
message.Subject = strSubject; message.IsBodyHtml = true;
// Message body content
message.Body = strContent;
// Send SMTP mail
smtpClient.Send(message);
}
catch (Exception ex)
{
throw ex;
}
}