AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=962&pId=-1
Working with Email Using ASP.NET 2.0
page
by Jason N. Gaylord
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 55415/ 56

Introduction

In ASP.NET 1.x sending email was fairly simple.  The only issue was that there were different ways to send email depending on whether the application was web or windows based.  Windows developers used MAPI to send emails using an email client like Outlook.  Web developers used CDOSYS to send rich emails.  Microsoft realized that a change was warranted.  In ASP.NET 2.0 Microsoft released a new set of classes to handle email.  The only issue is that to many developers, sending email became much more complex.  Within this article, we will walk through the changes to the web.config file, the new classes that are available and how to send email using the new MailMessage class.

Examining the Web.config

By now you should be familiar with the system.web section group that is found in the web.config file.  In ASP.NET 2.0 a new group was added that contains configurable sections for the System.Net namespace called the system.net section group.  This group allows email settings to be established by using the mailSettings section group.  Since we are sending emails and not receiving emails, we will use the SMTP protocol.  To define the SMTP settings, we will add the SMTP section group to the mailSettings section group.  The SMTP section group then contains a network section that specifies attributes for the SMTP network settings.  These attributes include host, port, username, and password.  An example of the system.net section group can be found in listing 1.

Listing 1

<system.net>
  <mailSettings>
    <smtp>
      <network host="mail.contoso.com" 
      userName="email@contoso.com" password="password" />
    </smtp>
  </mailSettings>
</system.net>
Accessing the Web.config from Code

To prevent confusion, in ASP.NET 2.0 the System.Web.Mail namespace has been marked deprecated.  All of the classes are still accessible using IntelliSense and will still function properly.  However, they too are marked obsolete.  Instead, a new namespace found at System.Net.Mail should be used.  This new namespace contains classes to manage your mail client and messages.  The SmtpClient class is used to establish a host, port, and network credentials for your SMTP server.  The MailMessage class is similar to the MailMessage class found in the old System.Web.Mail namespace.  This class allows a full email message to be built.  There is also an Attachment class that allows an attachment to be generated so it can later be added to the MailMessage object.  In addition to these three most commonly used classes, you will find that System.Net.Mail contains an AlternateView and LinkedResource class.

Unfortunately, ASP.NET 2.0 does not provide a clean and easy way to access the system.net section group from the web.config file within code.  The SmtpClient object contains a UseDefaultCredentials boolean property, but that specifies whether the SmtpClient object is to use the credentials of the user currently running the application.  Before we begin accessing the attributes in the web.config file, we will need to determine what credentials will be required to connect to the SMTP server and ensure that the values we will use will work.  In many cases, the credentials that would be used to connect to a Microsoft Exchange server would be different than those to connect to many ISP email systems.  In the example to follow we will use a username, password, and hostname.

The first task on our plate is to read the mailSettings section group from the web.config file.  To accomplish this task, we will need to create a new object of type System.Configuration.Configuration.  This object will store our web.config file.  We will assign this new object to the applications web.config by using the OpenWebConfiguration method of the WebConfigurationManager class.  The OpenWebConfiguration method will look for a relative path. We will pass in the HttpContext.Current.Request.ApplicationPath since we will want to load the web.config file for the current application.

The second task is to load the specific section group from the object that contains our web.config file into a new object.  A new object of type System.Net.Configuration.MailSettingsSectionGroup will be created.  This object will be assigned to the mailSettings section in the web.config file.  We will use the GetSectionGroup method of our configuration object to obtain this section.  ASP.NET does not know that the mailSettings section is found under system.net so we must specify the full section group as system.net/mailSettings.  An example of this can be seen in listing 2.

Listing 2

Dim config As System.Configuration.Configuration = _ 
    WebConfigurationManager.OpenWebConfiguration( _
    HttpContext.Current.Request.ApplicationPath)
Dim settings As System.Net.Configuration.MailSettingsSectionGroup = _ 
    CType(config.GetSectionGroup("system.net/mailSettings"), _
    System.Net.Configuration.MailSettingsSectionGroup)
Creating the SMTP Client

A new object of type SmtpClient will be created to act as the SMTP server for mail being sent out.  The SmtpClient object will need to have the network credentials passed into it.  Thus, we will need to create a new object of type System.Net.NetworkCredential and pass in the username and password values from the web.config.  These values can be found by assessing the Smtp.Network.Username and Smtp.Network.Password properties of the settings object defined earlier.  The NetworkCredential object will be assigned to the Credentials property of the SmtpClient object.  The other property we must set is the SmtpClient object's host property.  This too will be assigned a value from the settings object created earlier.  An example of this can be seen in the listing given below.

Listing 3

'Obtain the Network Credentials from the mailSettings section
Dim credential As New System.Net.NetworkCredential( _
    settings.Smtp.Network.UserName, settings.Smtp.Network.Password)
 
'Create the SMTP Client
Dim client As New SmtpClient()
client.Host = settings.Smtp.Network.Host
client.Credentials = credential
Creating a MailMessage Object

The MailMessage object in ASP.NET 2.0 is much more robust than the one found in the CDOSYS libraries in ASP.NET 1.x.  The new MailMessage object still contains all of the common properties that an email message has including To, From, Subject, and Body.  The To and From properties have changed a bit.  The From property is no longer "just a string."  Instead, the From property is of type MailAddress.  The To property is similar in that it is a collection of MailAddress objects.  Since the CC and Bcc properties have the same requirements as the To property, they too are a collection of MailAddress objects.  The MailMessage object contains some additional properties including, but not limited to, AlternateViews, Attachments, BodyEncoding, DeliveryNotificationOptions, IsBodyHtml, Priority, and ReplyTo.

The AlternateViews property allows an alternate view to be specified by passing in either a filename or a stream and assigning a MIME type to the view.  The Attachments property allows attachments to be added to the message.  The BodyEncoding property is a value that can specify the System.Text.Encoding type of the email message.  The DeliveryNotificationOptions property specifies when delivery notifications should be received.  The IsBodyHtml property is a boolean value signifying whether the email's body is HTML or plain text.  The Priority property specifies whether this email is of high, low, or normal importance.  The ReplyTo property is the email address that the reply message would go to.

To send the MailMessage object, the object must be passed into the Send method of the SmtpClient object.  An example of this can be seen in the listing below.

Listing 4

'Build Email Message
Dim email As New MailMessage
email.From = New MailAddress("email@contoso.com")
email.To.Add("steveb@contoso.com")
email.CC.Add("billg@contoso.com")
email.Subject = "Test Email"
email.IsBodyHtml = True
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
email.Body = "<strong>Hello Steve!</strong>"
 
'Send Email
client.Send(email)
Conclusion

As you can see now, sending email in ASP.NET 2.0 is much more complex.  However, it is also much more robust.  Many of the email options that you could not access before without adding an email header to the email message can now be added with properties.  Hopefully the team will continue to enhance this namespace and add additional functionality in the future.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 6:40:07 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search