ContactUs page with Capctcha in ASP.NET using C#


Using a contact form on your website is very useful as it helps your web site visitors to communicate with you in an easy and simple way. But, there are spammers and hackers who are looking for exploitable web forms. It is essential to secure your form against all 'holes' that those hackers are searching for .

If you are not validating your form fields (on the serve side) before sending the emails, then hackers can alter your email headers to send the bulk unsolicited emails.

 In this article will give tutorial how to create contact Us page with below key features

Key features:

  1. Contact Us form
  2. Validations
  3. Send Email
  4. Use of Captcha to avoid Spam

Contact Us Form

<div style="padding: 5px 0px 10px 150px">
        <div id="ContentTitle">
            <h1>
                Contact Us</h1>
        </div>
        <div id="ContentBody">
            <table cellpadding="2">

                <tr>
                    <td class="fieldname">
                        Email:
                    </td>
                    <td>
                          <asp:TextBox runat="server" ID="txtEmail" Width="100%" />
                    </td>
                    <td>
                      <asp:RequiredFieldValidator runat="server" Display="dynamic" ID="RequiredFieldValidator1"
                            SetFocusOnError="true" ControlToValidate="txtEmail" ErrorMessage="Your Email is required">*</asp:RequiredFieldValidator>
                    </td>
                </tr>            

                <tr>
                    <td class="fieldname">
                        <asp:Label runat="server" ID="lblName" AssociatedControlID="txtName" Text="Full name:" />
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtName" Width="100%" />
                    </td>
                    <td>
                        <asp:RequiredFieldValidator runat="server" Display="dynamic" ID="valRequireName"
                            SetFocusOnError="true" ControlToValidate="txtName" ErrorMessage="Your name is required">*</asp:RequiredFieldValidator>

                    </td>
                </tr>
                <tr>
                    <td class="fieldname">
                        <asp:Label runat="server" ID="lblBody" AssociatedControlID="txtBody" Text="Message:" />
                    </td>
                    <td>
                        <asp:TextBox runat="server" ID="txtBody" Width="100%" TextMode="MultiLine" Rows="8" />
                    </td>
                    <td>
                        <asp:RequiredFieldValidator runat="server" Display="dynamic" ID="valRequireBody"
                            SetFocusOnError="true" ControlToValidate="txtBody" ErrorMessage="The Message is required">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" class="fieldname" align="center">
                        <img src="CaptchaPage.aspx" alt="Catcha" /><br />
                        <p>
                            <strong>Enter the code shown above:</strong><br />
                            <asp:TextBox ID="CodeNumberTextBox" runat="server"></asp:TextBox>
                        </p>
                        <p>
                            <em class="notice">(Note: If you cannot read the numbers in the above<br>
                                image, reload the page to generate a new one.)</em>
                        </p>
                        <p>
                            <asp:Label ID="MessageLabel" runat="server" ForeColor="#CC0000"></asp:Label></p>
                    </td>
                </tr>
                <tr>
                    <td colspan="3" align="right">
                        <asp:Label runat="server" ID="lblFeedbackOK" Text="Your message has been successfully sent."
                            SkinID="FeedbackOK" Visible="false" ForeColor="#006600" Font-Bold="True" />
                        <asp:Label runat="server" ID="lblFeedbackKO" Text="Sorry, there was a problem sending your message."
                            SkinID="FeedbackKO" Visible="false" ForeColor="#CC0000" />
                        <asp:Button runat="server" ID="txtSubmit" Text="Send"
                            onclick="txtSubmit_Click" />
                        <asp:ValidationSummary runat="server" ID="valSummary" ShowSummary="false" ShowMessageBox="true" />
                    </td>
                </tr>
            </table>
        </div>
    </div>


Validating Captcha Image and Send Email

Below example will show you how to validate captcha Image before sending an Email to avoid spam mails

            MailMessage Message = new MailMessage();
            Message.From = new MailAddress(txtEmail.Text, txtName.Text + Page.User.Identity.Name);
            Message.To.Add(new MailAddress("[email protected]"));
            Message.Body = txtBody.Text;
            Message.Subject = "Contact Us";
            Message.IsBodyHtml = true;
            try
            {
                if (this.CodeNumberTextBox.Text == this.Session["CaptchaImageText"].ToString())
                {
                    this.MessageLabel.Text = "";
                    SmtpClient mailClient = new SmtpClient();
                    mailClient.Send(Message);
                    lblFeedbackOK.Visible = true;
 
                }
                else
                {
                    // Display an error message.
                    this.MessageLabel.Text = "ERROR: Incorrect, try again.";
                    // Clear the input and create a new random code.
                    this.CodeNumberTextBox.Text = "";
                    lblFeedbackOK.Visible = false;
                    this.Session["CaptchaImageText"] = GenerateRandomCode();
                }
 
            }
            catch (Exception ex)
            {
                lblFeedbackKO.Visible = true;
            }


first off you must import using System.Net.Mail; namespace. Then define new SMTP email and collect all the information user entered in your webpage. Finally send all the information to recipient as an email.

     <system.net>
    <mailSettings>
      <smtp from="yourdomain.com">
        <network host="mail.yourdomain.com" port="25" userName="xxx" password="xxx"/>
      </smtp>
    </mailSettings>
  </system.net>

 

Download the source code for more details.

Up Next
    Ebook Download
    View all
    Learn
    View all