Creating a Contact Form With ASP.NET   Download Sample Source Code

img

Emails are at the heart of our modern lifestyle, as a main form of communication over the Internet. Almost every application out there uses emails for marketing, information exchange and so much more.

In this exercise, we will go through the steps, to make “Contact US” form. In order to help you get started quickly, we have prepared a “getting started” package, that you may freely download.

Prerequisites

This tutorial is very simple, but assumes that you already have the following:

  • Visual Studio 2015 or newer installed on your machine.

  • An Account at ASPHost.net. If you don’t have one already, please subscribe here.

Implementation

1Project Creation

Let’s open Visual Studio, and create a new project. Select an ASP.NET web application and change the project name to “democontactus” then click “OK”.

Next, from the templates list, we can now proceed by selecting the “Web Forms” template

If you are prompted to setup an Azure account, you may click the “Cancel” button, as this subject is not part of the current tutorial.

img


The project creation process takes some time (from few seconds to few minutes depending on your system performance), so just be patient as it progresses.

img
2 Setting SMTP

In order to send emails, you need to configure an SMTP server.

SMTP stands for Simple Mail Transfer Protocol. It’s part of multiple emailing services and handles emails sending.

In our application, we will need to update the “web.config”, by adding the SMTP credentials we will be using to send emails from our application.

All you need to do is set the parameters following:

  • fromEmail => The email that will display as the sender address.
  • SMTPUser => The mail server username
  • SMTPPass => The corresponding password
  • Port => 587 for TLS
  • server => smtp.example.com<
3TheLayout / Design
 

<divclass="cus-contact-page">

<divclass="cus-form-outer">

<h3class="cus-heading">contact us</h3>

<div>

<formmethod="post"id="customcontact"onsubmit="return validate()"runat="server">

<pclass="cus-tagline">Please fill out the form below to contact us.</p>

<divclass="form-group">

<asp:LabelID="lblMsg"runat="server"CssClass="message"></asp:Label>

<divid="textname-error"class="error-box hide-err">

<spanclass="error-msg-box">error message</span>

</div>

<asp:TextBoxrunat="server"ID="textname"CssClass="inputcontrol"placeholder="Name"ClientIDMode="Static"/>

</div>

<divclass="form-group">

<divid="email-error"class="error-boxhide-err">

<spanclass="error-msg-box"></span>

</div>

<asp:TextBoxrunat="server"ID="email"CssClass="inputcontrol"ClientIDMode="Static"placeholder="Email Address"/>

</div>

<divclass="form-group">

<divid="subject-error"class="error-box hide-err">

<spanclass="error-msg-box">error message</span>

</div>

<asp:TextBoxrunat="server"ID="subject"CssClass="inputcontrol"ClientIDMode="Static"placeholder="Subject"/>

</div>

<divclass="form-group">

<divid="message-error"class="error-box hide-err">

<spanclass="error-msg-box">error message</span>

</div>

<asp:TextBoxID="message"runat="server"Columns="50"Rows="5"TextMode="MultiLine"CssClass="inputcontrol"ClientIDMode="Static"placeholder="Messege"></asp:TextBox>

</div>

<divclass="form-groupclearfix">

 

<asp:Buttonid="btnSubmit"runat="server"CssClass="btnbtn-primary"Text="Submit"></asp:Button>

</div>

</form>

</div>

</div>

</div>

img

The first 4 tags are standard HTML tags (div and h3).

Next comes the opening <form> tag, with 4 properties:

  • Method: HTTP Method
  • Id: unique identifier of the form
  • Onsubmit: a form submission event handler
  • Runat: specifies that this code will be run at the server side
Quick Reference

There are multiple HTTP methods, which are part of the HTTP protocol, like: POST, GET, PUT, DELETE (also used in REST APIs). Each method has it’s own specification and use case.

In this example we have used the POST method, which transfers the data inside the HTTP request header. Unlike the GET method, which sends the data in the URL in the form of a concatenated string: var1=value1&var2=value2… etc.

Next comes the Onsubmit event handler, which simply specifies that this form, and once submitted, will be handled by a function called: validate()

The other tags are simple input tags (TextBox, Labels and Buttons), which are used to display the form layout and data.

At this point, your form should look like the following:

img

You can switch to this view by clicking on the “Design” tab in Visual Studio.

4The Code

Now it’s time to make this form actually work, and it should do so by responding to a user’s click on the “Submit” button.

In order to add event handlers, we can either do so directly in the code, which is something you would want to do when you become proficient and experienced with the technology, but for now, we will use the simple way.

Make sure you are on the Design tab, and then double click on the “Submit” button. This is one of the situations when Visual Studio comes in handy: It has created a click “Event handler” automatically, which is simply a function with a lot of parameters.

           ProtectedSub btnSubmit_Click(sender AsObject, eAsEventArgs)HandlesbtnSubmit.Click
           

Before we finish this method, we will need another function that will handle email submission, let’s name it: sendmail

The sendmail method should look like this:
           

PublicSharedFunctionsendmail(ByVal From AsString, ByValReceiver AsString, ByValsubject AsString, ByValmessage AsString,

ByValSMTPUserAsString,ByValSMTPPassAsString,ByVal Port AsString,ByVal Host AsString,ByValsslAsString)AsBoolean

Dimmess AsMailMessage = NewMailMessage()

mess.From= NewMailAddress(From)

mess.To.Add(Receiver)

mess.Subject= subject

mess.IsBodyHtml= True

mess.BodyEncoding = System.Text.Encoding.UTF8

mess.Body = message

mess.Priority = MailPriority.Normal

 

Dimclient AsSmtpClient = NewSmtpClient()

client.UseDefaultCredentials = False

client.Credentials = NewSystem.Net.NetworkCredential(SMTPUser,SMTPPass) 'enter your user name and password for smtp server  

client.Port= Convert.ToInt32(Port) 'use465 or 587 ports

client.Host= Host

client.EnableSsl= Convert.ToBoolean(ssl) 'true

 

client.Send(mess)

 

ReturnTrue

This method will be used to send an email using your SMTP credentials, from the configuration parameters.

Now, back to the click event handler, let’s complete it with the code that retrieves the form’s data, and sends the email:

Try

DimstrBodyAsString

strBody= "<BR> Name: "&textname.Text

strBody+= "<BR> Email: "&email.Text

strBody+= " <BR><BR>Comment: " + message.Text

 

sendmail(My.Settings.fromEmail, My.Settings.toEmail, subject.Text, strBody,My.Settings.SMTPUser, My.Settings.SMTPPass,My.Settings.port, My.Settings.server,My.Settings.auth)

'sendtest()

lblMsg.Text= "Email has been sucessfully sent."

Catchex AsException

lblMsg.Text = ex.Message.ToString

EndTry

Finally, you may run the app to test the code we have just written. Run the application from Visual Studio, which will launch the browser. Fill in the required fields: Name, Email, Subject and Message, and click on the “Submit” button. If all goes well, an email will be sent right away.

img