Webmatrix Asp.net Razor Email Contact Form Example

Hi everyone,

When I have the time I am going to endeavour to share some of the basic code and techniques featured on the bigint.co.uk site.

Today, I am going to share the email contact form that can be seen here.

All I ask in return for the free code is that you visit the bigint.co.uk site by searching on Google or Bing for [Web Development Huddersfield] and then choosing the bigint.co.uk from the results.  You can also like us on our site.  If you are really grateful, you may wish to make a donation to heavy horse heritage using the button on the left.

Firstly the code.  I built the Bigint Ltd site using the ASP.NET Razor C# syntax.  There are two common approaches in tutorials online to developing an email contact form like ours using the WebMail Helper.  The first uses two pages; a page that contains the html mark up for the contact form and a page to process the request and return a response, such as “email sent”.

The second method in my opinion is slightly neater because the contact form mark up and the code for processing the request are contained in the same page; however, the WebMail helper code is also added to the _AppStart page which is an option in both approaches.  Today, we are going to look at the second approach.

If you are using a Webmatrix template you will probably already have a root file named _AppStart.cshtml, if not create one.

To make use of the WebMail Helper the following code needs adding to the _AppStart.cshtml page to define your SMTP server settings.  The SMTP server settings can be defined in the same page as the processing code and email form, or in the _AppStart page.  It is best practice to use the _AppStart page because users cannot access Razor pages that begin with an underscore “_”.  Putting the SMTP code and password in the page that contains the contact form will provide direct access to your account username and password which is extremely unsafe.

     WebMail.SmtpServer = "mailserver.example.com";
     WebMail.UserName = "Username@example.com";
     WebMail.Password = "Your-Password"
     WebMail.From = "Username@example.com";
     WebMail.EnableSsl = true; (add this if smtp is encrypted)
     WebMail.SmtpPort = 587;

You will need to change the SMTP settings in the code to match your email account and hosts server settings.

  • Mailserver.example.com should be changed to the name of your host’s SMTP server.
  • Username@example.com is the email address for your SMTP server account or the email address of the account you would like the emails to be sent to. This address can be used as the from address too.
  • Your-password is the password for your SMTP server account.  Again, this is usually your  host account password.
  • If you have secure SSL, which costs more with some hosts, mark ‘Enable SSL True’.
  • Finally set the correct SMTP port.

Please note that if you have a secure encrypted SSL connection you should use port 465; otherwise port 587 is the default for plain text emails.  If you are having issues though, try using port 25 which is usually an alternative port and might get you up and running with some hosts.

Next, we need a form and some code to process the request.  Create a new page and add the code below remembering to change Username@example.com for the email address of the account you would like the email to be sent to; this will normally be the same address you used for the username and from address in the SMTP settings above.

@{

    Layout = "/_SiteLayout.cshtml";
    Page.Title = "Contact Bigint Web Development Huddersfield";

    var message = "";
    var companyname = Request.Form["emailAddress"];
    var contactname = Request.Form["emailSubject"];
    var employeecount = Request.Form["emailBody"];

    try{
        if (IsPost && Validation.IsValid()) {

        // Send email
        WebMail.Send(to:"Username@example.com",
            subject: Request.Form["emailSubject"],

            body: "Help request from -   " + Request.Form["customerName"] + " - " + "Email Subject -   " + Request.Form["emailSubject"]  + " - " + "Customer email -   " + Request.Form["emailAddress"]
           );
           message = "Email sent!";
        }
    }
    catch(Exception ex){
        message = "Email could not be sent!";
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
</head>

  <body>
    <h1>Test Email</h1>

    <form method="post">
       <p>
        <label for="customerName">Name:</label>
        <input type="text" name="customerName" placeholder="e.g. Joe Bloggs" required />
       </p>
      <p>
        <label for="emailAddress">Email address:</label>
        <input type="email" name="emailAddress" placeholder="e.g. me@me.com" required />
      </p>
      <p>
        <label for="emailSubject">Subject:</label>
        <input type="text" name="emailSubject" placeholder="e.g. Quote Request" required /> 

      </p>
      <p>
        <label for="emailBody">Text to send:</label><br/>
        <textarea name="emailBody" rows="6" placeholder="Request"  required></textarea>
       </p>
    <p><input type="submit" value="Send!" /></p>
    @if(IsPost){
        <p>@message</p>
    }
    </form>
  </body>
</html>

You may have noticed that I have added some additional functionality to the contact form.  Validation has been incorporated by adding “required” to the text input fields.  The form will not submit until all the required fields have been completed correctly.

Also, the placeholder attribute has been added to pre-populate the text input fields to prompt users.

If the email is sent successfully a message appears showing, “Email sent!”.  If there is a problem with the settings you will see, “Email could not be sent!”

If you have custom errors turned on in your web.config file it will be more difficult to diagnose the problem.  Instead, switch custom errors to off – <customErrors mode=”Off”>.  You can then use the more accurate browser error messages to get to the root of the problem.

Finally, the styling.  I used Twitter Bootstrap to style aspects of the bigint.co.uk website.  When I built the site Bootstrap version 2.3.2 was out; although, the package has since been updated.

If you don’t know what Bootstrap is, you should read up because it’s great, looks cool and can save you a lot of time.  In brief, Bootstrap adds styling to html mark up wherever the appropriate class is given to an object.  Bootstrap has already been well documented; so, I am not going to reinvent the wheel.

All you need to do is drop the Bootstrap assets folder into the root of your site and then link to the style sheets by adding the links below into the head section of the page.

Then, when you create a html object such as a form give it a form class from the Bootstrap documentation like I have done below.  This will apply the pre-defined CSS styling.

        <!-- Le Bootstrap Styles -->
       <link href="assets/css/bootstrap.css" rel="stylesheet">
       <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">

Bootstrap v2.3.2 download is available here.

For your convenience I have even included our full contact form styled with Bootstrap – below.  Just remember to add the Bootstrap assets folder to the root of your site.  Voila!

@{
    Layout = "_SiteLayout.cshtml";
    Page.Title = "Contact Us | Huddersfield Website Design | Web Hosting";

    var message = "";
    var emailAddress = Request.Form["emailAddress"];
    var emailSubject = Request.Form["emailSubject"];
    var emailBody = Request.Form["emailBody"];

    try{
        if (IsPost && Validation.IsValid()) {

        // Send email
        WebMail.Send(to:"Username@example.com",
            subject: Request.Form["emailSubject"],

            body: "Help request from -   " + Request.Form["customerName"] + " - " + "Email Subject -   " + Request.Form["emailSubject"]  + " - " + "Customer email -   " + Request.Form["emailAddress"]  + " - " + "Request -   " + Request.Form["emailBody"]
           );
           message = "Thank you, Email sent!";
        }
    }
    catch(Exception ex){
        message = "Email could not be sent!";
    }
}

<!DOCTYPE html>

<html lang="en">

    <head>
        <meta charset="utf-8" />
            <title>Contact Us | Huddersfield Website Design | Web Hosting</title>

            <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>	          

      <div class="row">

          <div class='well span5'>

            <form class='form-stacked' method="post">

 <div style="text-align: center; margin-top: 20px; font-size: 16px; font-weight: bold; color: green">
@if(IsPost){
<span class="alert alert-success">@message</span>
}
</div>

<h2>Email Contact Form</h2>

</br>

<!-- Text input-->
<div class="control-group">
  <label class="control-label">Full Name</label>
  <div class="controls">
    <input id="customerName" name="customerName" value="@Request.Form["customerName"]" placeholder="e.g. Joe Bloggs" class="input-xlarge" required="" type="text">
 </div>
</div>

<!-- Text input-->
<div class="control-group">
  <label class="control-label">Subject</label>
  <div class="controls">
    <input id="emailSubject" name="emailSubject" value="@emailSubject" placeholder="e.g. Quote Request" class="input-xlarge" required="" type="text">
</div>
</div>

<!-- Text input-->
<div class="control-group">
  <label class="control-label">Email Address</label>
  <div class="controls">
    <input id="emailAddress" name="emailAddress" value="@Request.Form["emailAddress"]" type="email" placeholder="e.g. me@me.com" class="input-xlarge" required="" type="text">
   </div>
</div>

<!-- Textarea -->
<div class="control-group">
  <label class="control-label">Text Area</label>
  <div class="controls">
    <textarea class="span4" id="emailBody" name="emailBody" rows="10" placeholder="Request" required></textarea>
  </div>
</div>

<!-- Button -->
<div class="control-group">
  <label class="control-label"></label>
  <div class="controls">
    <button id="singlebutton" name="singlebutton" class="btn btn-success">Send</button>

     <input value='Reset' class="btn" type="reset"/>
  </div>
</div>

  <p style="text-align: center; color: green">Refresh page to re-send.</p>

</form>
</div>

 <div class='span4'>

          <h3 style="padding-left: 20px">Contact Information</h3>
          <p style="padding-left: 20px"><strong>Email: </strong>bigint.contact@gmail.com<br/>
          <strong>Phone: </strong>01484 473191</p>

          <div class='cleaner_h10'></div>
          <h3 style="padding-left: 20px">Address</h3>
<address style="padding-left: 20px">
<strong><abbr title="New Hudderfield Office">Bigint</abbr></strong><br>
3M Buckley Innovation Centre<br>
Huddersfield, HD1 3BD<br>
</address>

         <div class='cleaner_h10'></div>
          <h3 style="padding-left: 20px">Find Us</h3>
          <div class='span6'>
          <br /><small><a href="https://maps.google.co.uk/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=3m+buckley+innovation+center,+firth+street+huddersfield&amp;aq=&amp;sll=53.741446,-1.686054&amp;sspn=0.472705,0.699005&amp;ie=UTF8&amp;hq=&amp;hnear=3M+Buckley+Innovation+Centre,+Firth+St,+Huddersfield,+West+Yorkshire+HD1+3BD,+United+Kingdom&amp;t=m&amp;ll=53.641585,-1.777039&amp;spn=0.015265,0.029182&amp;z=14&amp;iwloc=A" style="color:#0000FF;text-align:left">View Larger Map</a></small>
         </div>

        </div>
</div> 

    </body>
</html>
      <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->

    <script src="assets/js/bootstrap-transition.js"></script>
    <script src="assets/js/bootstrap-alert.js"></script>
    <script src="assets/js/bootstrap-modal.js"></script>
    <script src="assets/js/bootstrap-dropdown.js"></script>
    <script src="assets/js/bootstrap-scrollspy.js"></script>
    <script src="assets/js/bootstrap-tab.js"></script>
    <script src="assets/js/bootstrap-tooltip.js"></script>
    <script src="assets/js/bootstrap-popover.js"></script>
    <script src="assets/js/bootstrap-button.js"></script>
    <script src="assets/js/bootstrap-collapse.js"></script>
    <script src="assets/js/bootstrap-carousel.js"></script>
    <script src="assets/js/bootstrap-typeahead.js"></script>

That’s all you should need in order to get a working email contact form like ours.

Bigint Contact Form

Find us on Google+ here

 

Advertisements