Tuesday, July 18, 2006

 

Asp.NET : Sending Emails from ASP.NET 2.0

Sending Emails from ASP.NET is very easy. In .NET 1.1 and 1.0, the class was System.Web.Mail but in .NET 2.0, they changed to System.Net.Mail.

The code for sending an email is given below

VB.NET

Dim email As MailMessage
Dim mailClient As SmtpClient

email = New MailMessage(fromAdd, toAdd, subject, message)

‘if you want to send HTML message set this property to true
email.IsBodyHtml = True

mailClient = New SmtpClient(”Your mail server name”) ‘like mail.xxx.com

‘ if your server is using different port then set this
mailClient.Port = [PortNumber]

mailClient.Send(email)

Some times your outgoing SMTP server may need username and password. Then you need to modify the code little bit.

First create an object of NetworkCredential (This is available in the System.Net Namespace) with the username and password

Dim authInfo As New NetworkCredential(smtpUsername, smtpPassword)

Then set the UseDefaultCredentials property of the smtp client object to false and set the Credentials property of the smtp client object to authInfo. Then send the mail.

mailClient.UseDefaultCredentials = False
mailClient.Credentials = authInfo


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?