Staying in Touch – How to Build a Contact Form

Whether you are a Fortune 500 company or a mom-and-pop shop online, you need some way for visitors to contact you. Most contact forms are pretty much the same, you choose what information you want your visitors to provide to you as well as an open area for any comments/questions they would like to leave. The information is then sent to an administrator email account for correspondence. You may also want to display a confirmation to the user that their email has been sent.

To demonstrate how to do this, I will use my own contact form in ASP.NET (VB.NET) and an old PHP version I used to run a long time ago.

ASP.NET

For those of you Microsoft-based developers, here is some sample code that can be used as a base for your contact forms.

ASPX (frontend)

<h1>Contact Nicholas Barger</h1>
<p>Please feel free to contact me with questions, comments, or anything else that you would like to discuss. I appreciate your interest/involvement so I try and respond as quickly as possible.</p>

<p>You can also find me on <i>LinkedIn</i> at: <a href="http://www.linkedin.com/in/nicholasbarger" target="_blank">http://www.linkedin.com/in/nicholasbarger</a></p>

<div class="formdisplay">
	<span>Please enter your email address:</span><br />
	<asp:TextBox ID="tbEmail" runat="server" Width="700px"></asp:TextBox><br />
	<span>Please enter a subject for this message:</span><br />
	<asp:TextBox ID="tbSubject" runat="server" Width="700px"></asp:TextBox><br />
	<span>Please enter your message below:</span><br />
	<asp:TextBox ID="tbMessage" runat="server" TextMode="MultiLine" Width="700px" Height="250px"></asp:TextBox><br />
</div>

<asp:Button ID="btnSubmit" runat="server" Text="Send Message" />

VB.NET (backend/codebehind)

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
	'Prep basic values
	Dim strFromEmail As String = tbEmail.Text
	Dim strToEmail As String = ConfigurationManager.AppSettings("AdminEmail")
	Dim strSubject As String = tbSubject.Text

	'Prep custom values
	Dim strBody As String = ""
	Dim strFromName As String = ""

	strBody = tbMessage.Text

	Dim oCommonFunc As New Common.Functions
	Try
		oCommonFunc.sendEmail(strFromEmail, strFromName, strToEmail, strSubject, strBody, Nothing, Nothing, Nothing, True)
		Response.Redirect("contactcomplete.aspx")
	Catch ex As Exception
		'TODO - Display Error Message
	Finally
		oCommonFunc = Nothing
	End Try
End Sub

VB.NET (common class/codebehind)

Public Function sendEmail(ByVal strFromEmail As String, _
	ByVal strFromName As String, _
	ByVal strToEmail As String, _
	ByVal strSubject As String, _
	ByVal strBody As String, _
	Optional ByVal strCCEmail As String = Nothing, _
	Optional ByVal strBCCEmail As String = Nothing, _
	Optional ByVal strAttachmentPath As String = Nothing, _
	Optional ByVal bIsHTML As Boolean = False) As Boolean

	'Check for proper from email
	If String.IsNullOrEmpty(strFromEmail) = True Then
		Throw New Exception("From email is not specified.")
	End If

	'Check for proper to email
	If String.IsNullOrEmpty(strToEmail) = True Then
		Throw New Exception("To email is not specified.")
	End If

	'Check for a non-empty message subject
	If String.IsNullOrEmpty(strSubject) = True Then
		Throw New Exception("Subject was not specified.")
	End If

	'Check for a non-empty message body
	If String.IsNullOrEmpty(strBody) = True Then
		Throw New Exception("Body of email was not specified.")
	End If

	'Create mail object
	Dim oMail As New MailMessage()
	'oMail.Host = ConfigurationManager.AppSettings("MailHost")

	'Convert all "," into ";"
	strToEmail = strToEmail.Replace(",", ";")

	'Check if "To" email contains multiple emails
	If strToEmail.IndexOf(";") >= 0 Then 'add multiple emails
		Dim strToArray As String() = Split(strToEmail, ";")
		For i As Integer = 0 To strToArray.Length - 1
			oMail.To.Add(strToArray(i))
		Next
	Else 'add single email
		oMail.To.Add(strToEmail)
	End If

	'If CC exists
	If String.IsNullOrEmpty(strCCEmail) = False Then
		'Convert all "," into ";"
		strCCEmail = strCCEmail.Replace(",", ";")

		'Check if "CC" email contains multiple emails
		If strCCEmail.IndexOf(";") >= 0 Then 'add multiple emails
			Dim strCCArray As String() = Split(strCCEmail, ";")
			For i As Integer = 0 To strCCArray.Length - 1
				oMail.CC.Add(strCCArray(i))
			Next
		Else 'add single email
			oMail.CC.Add(strCCEmail)
		End If
	End If

	'If BCC Exists
	If String.IsNullOrEmpty(strBCCEmail) = False Then
		'Convert all "," into ";"
		strBCCEmail = strBCCEmail.Replace(",", ";")

		'Check if "BCC" email contains multiple emails
		If strBCCEmail.IndexOf(";") >= 0 Then 'add multiple emails
			Dim strBCCArray As String() = Split(strBCCEmail, ";")
			For i As Integer = 0 To strBCCArray.Length - 1
				oMail.Bcc.Add(strBCCArray(i))
			Next
		Else 'add single email
			oMail.Bcc.Add(strBCCEmail)
		End If
	End If

	'Add additional information to mail object
	oMail.From = New MailAddress(strFromEmail, strFromName)

	oMail.Subject = strSubject
	oMail.Body = strBody

	If bIsHTML = True Then
		'oMail.IsHTML = True
		oMail.IsBodyHtml = True
	End If

	Dim strSMTPUserName As String = ConfigurationManager.AppSettings("SMTPEmail")
	Dim strSMTPPassword As String = ConfigurationManager.AppSettings("SMTPPassword")

	Dim smtpClient As New SmtpClient(ConfigurationManager.AppSettings("MailHost"))
	smtpClient.Credentials = New Net.NetworkCredential(strSMTPUserName, strSMTPPassword)

	oMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure

	If String.IsNullOrEmpty(strFromEmail) = False Then
		oMail.ReplyTo = New MailAddress(strFromEmail)
	End If

	If String.IsNullOrEmpty(strFromEmail) = False Then
		oMail.Headers.Add("Return-Path", strFromEmail)
		oMail.Headers.Add("Errors-To", strFromEmail)
		oMail.Headers.Add("Bounces_To", strFromEmail)
	End If

	'Add attachment
	If String.IsNullOrEmpty(strAttachmentPath) = False Then
		oMail.Attachments.Add(New Attachment(strAttachmentPath))
	End If

	'Send email
	Try
		smtpClient.Send(oMail)
	Catch ex As Exception
		Return getErrorMessage(ErrorMessage.ErrorSendingEmail)
	Finally
		oMail = Nothing
	End Try

	Return True
End Function

PHP

And now for all things open-source, a PHP version.

Disclaimer: I haven’t professionally worked with PHP since 2004, so if you have any suggestions to improve the code please add them to the comments.

All-In-One (spaghetti-code)

<?php
if(isset($_POST['btnSubmit'])) { 
	$mailto = "nicholas@nicholasbarger.com";
	$email = $_POST['tbEmail'];
	$subject = $_POST['tbSubject'];
	$message = $_POST['tbMessage'];
	$headers = 'From: $mailto'."\r\n"
.'Reply-To: $mailto'."\r\n";

	#Mail to Administrator
	if(mail($mailto, $subject, $message, $headers))
	{
		 header('Location:contact_complete.php');
	}
	else
	{
		//Display an error
	}
}
?>

<html>
<head>
	<title>PHP Contact Page Demo</title>
</head>
<body>
<h1>Contact Nicholas Barger</h1>
<p>Please feel free to contact me with questions, comments, or anything else that you would like to discuss. I appreciate your interest/involvement so I try and respond as quickly as possible.</p>

<p>You can also find me on <i>LinkedIn</i> at: <a href="http://www.linkedin.com/in/nicholasbarger" target="_blank">http://www.linkedin.com/in/nicholasbarger</a></p>

<div class="formdisplay">
	<span>Please enter your email address:</span><br />
	<input type="text" id="tbEmail" name="tbEmail" style="width:700px;"></input><br />
	<span>Please enter a subject for this message:</span><br />
	<input type="text" id="tbSubject" name="tbSubject" style="width:700px;"></input><br />
	<span>Please enter your message below:</span><br />
	<textarea id="tbMessage" name="tbMessage" style="width:700px; height:250px;"></textarea><br />
</div>

<input type="submit" id="btnSubmit" name="btnSubmit" value="Send Message" />
</body>
</html>

Make It Your Own

What I’ve outlined here is just a beginning demonstration. There is still work to be done, such as creating the contact complete page and notifying users that they successfully (or unsucessfully) contacted an administrator. Additionally, you may want to add additional fields to be captured, add field validation to ensure proper data entry, or perhaps add a confirmation email response to the user as well.

Have fun with it, and take a boring contact page and make it something really powerful. Hope this was helpful in getting you started, or refreshed on how to stay in touch with your visitors through a simple contact form!

2 thoughts on “Staying in Touch – How to Build a Contact Form

Leave a reply to Opelmimberb Cancel reply