Tuesday, March 6, 2007

Sending email in ASP .NET 2

In asp.net application it may needed to send an email to specefic email address. In ASP .Net 1 and 1.1 it was so simple to send an email, as it 's in ASP .NET 2.0.

In ASP .NET 1.1 we just create a MailMessage object from the System.Web.Mail namespace setting the properties and send that mail. Just like this:

MailMessage m = new MailMessage();
m.Body = “Mail Body Text”
m.BodyEncoding = System.Text.Encoding.UTF8;
m.BodyFormat = MailFormat.Html;
m.To = "SbElse@AnotherWebSite.com";
m.Subject = ”Mail Subject”;
m.From = "Somebody@AWebSite.com";
m.Priority = MailPriority.High;


ASP .NET team in the 2.0 version decided to move the System.Net.Mail instead of System.Web.Mail.
Actually System.Net.Mail is a new namespace which contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. (as Microsoft Says)

Anyway, for sending mail in ASP .NET 2.0 , I just create a MailMessage and set the properties of that, and at the end I use a SmtpClient object to send the mail message, like this:

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("From@WebSite.com","To@WebSite.com");
message.Subject = "Here is the subject";
message.Body = "Body of the message";
message.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure;
message.Priority = System.Net.Mail.MailPriority.High;

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.UseDefaultCredentials = true;

I used the UseDefaultCredentials becuase for some SMTP servers it requires to authenticate for sending mail. So this information can be setted in web.config file when UseDefaultCredentials is true.

Finally, I set these configuration settings on the web.config file like this:

<smtp from="user@host.com">
<network userName="user@host.com" password="pass" host="localhost">

notice that the host attribute of the network entity is the SMTP mail server address. Which I used localhost in this sample.

I hope it can help you.

1 comment:

Anonymous said...

good job, it works very well !!!!!