21.7. Sending Mail


You want the user of your application to be able to send email.


Create a form to allow the user to enter the email information. When the user submits the form to the server, build a MailMessage object from the email information and then send the email using the SmtpClient class.

In the .aspx file:

  1. Create a form to capture the sender’s email address, the recipient’s email address, the subject, and the message.

  2. Add a Send button that initiates the sending of the email.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Create a MailMessage object, which is used as a container for the mail message, setting the sender email address, recipient email address, subject, and body using the constructor parameters.

  2. Create a SmtpClient object setting the email server using the constructor parameter.

  3. Call the Send method to perform the send operation.

Examples 21-18, 21-19 through 21-20 show the .aspx file and the VB and C# code-behind files for an application we’ve written to demonstrate this solution. The output of the application is shown in Figure 21-6.


Sending email is a common requirement in web applications. In classic ASP, third-party controls are required to send email. In ASP.NET, all of the functionality required to send email is provided and is very easy to use.

Send email form output

Figure 21-6. Send email form output

To send email, you need ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.