O'Reilly logo

ASP.NET Cookbook by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.7. Sending Mail

Problem

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

Solution

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 SmtpMail 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.

  2. Set the To, From, Subject, and Body properties to the data entered on the form.

  3. Set the SmtpServer property of the SmtpMail class to the server that will send the email, and then call the Send method to perform the send operation.

Example 18-18 through Example 18-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 18-6.

Send mail form output

Figure 18-6. Send mail form output

Discussion

Sending email is a common requirement in ASP.NET 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.

To send email, you need the sender’s ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required