This tutorial will demonstrate how to add a simple Contact Us form for users to leave feedback via email in ASP.NET and C#.

Setting Up the Form

At this point in the tutorial I have created a new ASP.NET Empty Web Site in Microsoft Visual Studio and have added in a blank Web Form named Default.aspx. What we need to do now is setup a simple form to collect the data from the user. This will include a Name, Subject, and Message. Also, we will need a submit button that the user will click to send the email, and a label to show a result if the email was sent or not.

To do this, open up Default.aspx to source mode and add the following code in the div tag:

If you then open the Default.aspx page up to design mode you should see a table that looks similar to this:

SS1.gif

Adding the Code

The next thing we need to do is add the code to send the data from the form to our email address in the event that the submit button is clicked. To do this, double click the submit button to generate the Click event method for that button. Now in the Default.aspx.cs file, we will want to add in a few using statements that will allow us to send this email. Under the other using statements, add the following:

Next, we need to add some code to the Button’s Click event method. The following code is a template for sending an email using a Gmail account, however you will need to customize this based on the RecipientAddress, which will be the email you are sending the message to, the SenderAddress, which will be the email account you will be sending the message from and also the SMTP server and port that are appropriate for your email provider.

Here we have added code to create a new MailMessage object that will be sent via an SmtpClient object that will be configured based on an email address that we already have. The message object is populated with the data from the form and an email address to send it to. The SmtpClient is populated with the correct SMTP settings for the provider and email you are sending the message from. Then, the message is sent and the result label is changed to the appropriate text while the rest of the form is cleared.

To test this, simply check the email address that you have sent the message to and verify that an email has been sent and its contents are correct.
Download Source Files