Saturday, September 6, 2008

Send e-mail in ASp.Net 2.0 and onwards in C#

The following code example can be used to send email using Asp.Net in 2.0 and higher versions version.

The Namespace of email class is changed to System.Net.Mail from System.Web.Mail.

Import the System.Net.Mail Namespace
using System.Net.Mail;

Code:

MailMessage mail = new MailMessage();
mail.From = new MailAddress(”info@yourDomain.com”,”Alert”);
mail.To.Add(”you@yourdomain.com”);
mail.Subject = “mail test”;
mail.IsBodyHtml = true;
mail.Body = “Your message here”;
SmtpClient smtp = new SmtpClient(”mail.yourdomain.com”);
smtp.Credentials = new System.Net.NetworkCredential(”info@yourdomain.com”,”password of this info”);
smtp.Send(mail);

Note:
The email address specified in the “FROM” field must be valid and it need to be of your domain.
In the SmtpServer the domain name must be same as of your domain on which website is hosted.

Click here to download full source-code for this post

No comments: