Microsoft & .NETASPUsing ASP.NET To Send Email

Using ASP.NET To Send Email

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

E-mail is one of the most common and reliable methods of communication for both personal and business purposes. It also plays an important role in each and every Web site. This role will be in the type of automated e-mails from the server after posting information from a form. You may have noticed these types of e-mails while registering on a site. As soon as you post the form, the server will send an e-mail asking you to confirm either your registration or with the information you entered. If you have to confirm the registration, the server will send you a long URL that you have to click to proceed further with the registration process. A classic example of this functionality is ASP.NET forums. As soon as you register, you will be e-mailed a random password. You will also get e-mails after your post has been accepted by a moderator or if somebody replies to your post. If you are wondering that this is a server magic—it is not. The whole process is made possible with the help of server-side programming languages such as ASP and ASP.NET.

Classic ASP provided a component named CDONTS that a developer should use intelligently to provide e-mail functionality on his or her applications. But this component lacked major functionalities. You can easily send an e-mail, but the process is very difficult for sending e-mails with attachments, HTML versions, and so forth. Almost all server-side languages provide some sort of solution for achieving these tasks. But, ASP.NET simplified the work of developers with the introduction of a special .NET namespace called System.Web.Mail. Moreover, it is very tedious to upload a file to a server with ASP. You have to depend upon third-party components. ASP.NET ships with a cute built-in uploading capability with which your users can easily upload their files. They can also send the file as an attachment along with their e-mails. In this article, you will learn how to send different types of e-mails with ASP.NET.

To send e-mails, you should require access to a server with .NET Framework and SMTP enabled on it. SMTP stands for Simple Mail Transfer Protocol and e-mails are sent using this protocol. If you don’t have a paid server space, you can register for a free ASP.NET hosting account at a site such as http://europe.webmatrixhosting.net/.

The .NET Framework supplies a SMTP class that enables you to send a simple e-mail message. If you have to send an e-mail with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can insert attachments, set priorities, and much more, very easily. You can also send HTML e-mail using this class.

Sending a Simple E-Mail Message

To send an e-mail with a simple text message, you have to use the Send() method of SMTP class. The syntax of the Send() method is shown in Listing 1.1 and an example is shown in Listing 1.2:

Listing 1.1

[Visual C# .NET]

SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY");

[Visual Basic .NET]

SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY")

Listing 1.2

[Visual C# .NET]

SmtpMail.Send("info@mydomain.com","hello@hello.com","Thank You",
              "We look forward to working with you again in the
               future");

[Visual Basic .NET]

SmtpMail.Send("info@mydomain.com","hello@hello.com","Thank You", _
              "We look forward to working with you again in the _
               future")

You can place the above code either on the form’s Load() event or in a button control.

Sending E-Mail Messages Using WebForm Controls

The main problem with the code given in Listing 1.2 is that you have to change the parameter values each time for sending different mail messages. To solve this problem, you should build a User Interface using the required WebForm controls, as shown in Figure 1.

Figure 1: The User Interface

As you can see, the above User Interface is made up of two text boxes, one multiline text box, and a button. I have also applied ASP.NET validation controls to the above GUI to avoid errors. For more information regarding the usage of validation controls, refer to my previous articles Performing Validations with ASP.NET — Part 1 and Performing Validations with ASP.NET — Part 2.

Instead of supplying all parameters in the Send() method, you can define properties and their corresponding values separately by creating an instance of the MailMessage class. With the help of this class, you can easily add attachments, set priorities, BCC, CC values, and much more. Table 1, given at the end of this article, shows a list of properties of the MailMessage class. Add the code given in Listing 1.3 by double-clicking the button captioned Submit:

Listing 1.3

[Visual C# .NET]

MailMessage objEmail          = new MailMessage();
            objEmail.To       = txtTo.Text;
            objEmail.From     = txtFrom.Text;
            objEmail.Cc       = txtCc.Text;
            objEmail.Subject  = "Test Email";
            objEmail.Body     = txtName.Text + ", " +
                                txtComments.Text;
            objEmail.Priority = MailPriority.High;
  //SmtpMail.SmtpServer = "localhost";
  try{
    SmtpMail.Send(objEmail);
    Response.Write("Your Email has been sent sucessfully -
                    Thank You");
  }
  catch (Exception exc){
    Response.Write("Send failure: " + exc.ToString());
  }

[Visual Basic .NET]

  Dim objEmail as New MailMessage()
      objEmail.To       = txtTo.Text
      objEmail.From     = txtFrom.Text
      objEmail.Cc       = txtCc.Text
      objEmail.Subject  = "Test Email"
      objEmail.Body     = txtName.Text & ", " &txtComments.Text
      objEmail.Priority = MailPriority.High
  'SmtpMail.SmtpServer  = "localhost"
  try
    SmtpMail.Send(EMail)
    Response.Write(Your E-mail has been sent sucessfully - _
                   Thank You)

  catch exc as Exception
    Response.Write("Send failure: " + exc.ToString())
  End Try

Note: If you are using your local system (Server = localhost) instead of a real live server, you should properly enable relying on the Internet Information Server (IIS).

When you execute the above code, the server not only displays a confirmation message but also sends an e-mail to the address mentioned in the To and Cc text boxes with the information you entered in the respective fields. It is not necessary for you to enter a Cc address, but it is shown here as part of the explanation. Further, the e-mail will be sent with the highest priority.

Table 1: MailMessage class properties

Property Description
Attachments Used for sending e-mails with attachments
From Sender’s e-mail address
To Recipient’s e-mail address
Cc Recipient’s e-mail address (Carbon Copy)
Bcc Recipient’s e-mail address (Blind Carbon Copy)
Body Text of the e-mail message
BodyFormat Specifies the format of an e-mail message (Possible Values: Text, Html)
Priority Specifies the priority of an e-mail message (Possible Values: High, Low, and Normal)
Subject Denotes the subject of an e-mail message
Headers Denotes a collection of acceptable headers (Example: Reply-To)
BodyEncoding Specifies the method of encoding an e-mail message (Possible Values: Base64 and UUEncode)

Sending HTML E-Mail Messages

If you would like to send the above e-mail in HTML Format, simply add the code given below to the above listing:

[Visual C# .NET]

objEmail.BodyFormat = MailFormat.Html;

[Visual Basic .NET]

objEmail.BodyFormat = MailFormat.Html

You can download the complete source code by clicking here.

About the Author

Anand Narayanaswamy, a Microsoft Most Valuable Professional, works as an independent consultant and technical writer. Anand runs learnXpress.com and specializes in C#, ASP.NET, Visual Basic .NET, ASP, Visual Basic 6.0, and in the development of courseware, technical articles, documentation, and reviews of products and books. You can post your queries regarding this article at www.learnxpress.com/forums. Reach him at ananddotnet@yahoo.co.in.

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories