Hyvor Developer

PHP Contact Form - The Email Method

Without a contact us page anyone won't be able to have a complete website. All the internet users worldwide use contact us pages to connect with website owners for different reasons.

There are several methods that websites use for "contact us" pages. Real-time messaging is a great approach for this. But, it costs more. So, still, many websites use the email method which we are going to discuss in this article.

The Email Method is very simple to understand. First, we will have a page that basically has two input fields for email and message. The user should enter his email and a text describing his thoughts/needs in these input fields respectively and submit the form. Then, we send an email to an email address that you own like [email protected] or [email protected] This email includes the header Reply-To with the value of the user's email. So, you can easily reply to the user using your email service provider.

The Basis of email method contact form

Let's start! First, we gonna plan it.

Creating the HTML Form

Here's the HTML code I'll be using. Use the POST method and empty action attribute for the form element. (Empty action attribute will say the browser to submit the form to the same page). If you are not familiar with using forms in PHP, I recommend you to follow our complete tutorial on PHP forms.


<html>
<head>
	<title>PHP Contact Form - The Email Method - Hyvor Developer</title>
</head>
<body>

<form method="POST" action=""> 
	<div class="input-wrap">
		<span class="label">Email:</span>
		<input type="text" name="email">
	</div>
	<div class="input-wrap">
		<span class="label">Message:</span>
		<textarea name="message"></textarea>
	</div>
	<div class="input-wrap">
		<input type="submit" name="submit" value="Submit" class="submit-button">
	</div>

</form>

</body>
</html>


Our form has two input fields. First one is for the email of the user. The second one is a textarea which lets the user type a long message.

Sending the Email with PHP

We have already created the HTML page. To make it live we should add some PHP code to send an email to our email. Let me remind you our procedure again.

  • First, the client submits the form.
  • Then, we get client's email and message.
  • Next, we send ourselves a beautiful email including the user's message.
  • Important: In this email, we include a header called Reply-To. It is set to the client's email.
  • Because of this header, when we reply the email will be sent to the client's email.
  • Thereafter conversation should be continued through emails.

Let's look at the PHP code. Normally keeping the PHP code and HTML in the same page is better (but, not required). Here I'll keep both codes on the same page. I divide this into 4 subtopics.

  1. Checking for form submission
  2. Checking, collecting and validating submitted data
  3. Creating the email
  4. Sending the email
  5. Reporting errors

1. Checking for form submission

It's pretty easy. As we are using POST method for the form submission, we can always use the following code to check whether the HTTP request is a form submission or not.


<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// your other code here
}


When we enter a link into the browser, it sends a GET request to the server by default. So, if the request method is POST, the client must have completed the form and submitted. But, we are not 100% sure as someone can use terminal or software to send POST requests. In this case, we really need the next step to validate whether all the data is there.

2. Checking, collecting and validating submitted data

In this step, first, we check whether all the required data is set. If they are empty we store an error message in a variable to use in step 5. If they aren't empty, we assign them to variables. Then, we validate them. If they fail the validation we store an error again. (If you wanna learn how to validate inputs, please read our tutorial on it.


<?php
if ($_SERVER['REQUEST_METHOD'] === "POST") {
	if (empty($_POST['email'])) {
		$emailError = 'Email is empty';
	} else {
		$email = $_POST['email'];
		// validating the email
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$emailError = 'Invalid email';
		}
	}

	if (empty($_POST['message'])) {
		$messageError = 'Message is empty';
	} else {
		$message = $_POST['message'];
	}
}


3. Creating the email

First of all, we need to check whether there's no error.


if (empty($emailError) && empty($messageError)) {
	// all the code should go here
}


"Being nice is nice". So, first, we gonna create a simple and pleasant email which our minds force us to read. In this email, I'm gonna show the message of the user, time of submission and user's email. After the above steps now we have user's email in $email variable and message in $message variable. (I thought of keeping this simple, but I always like nice looking email designs as they help us to get the information correctly. So, I have used HTML in the email.)

First, we should generate the current date with PHP.


$date = date('j, F Y h:i A');


Now, we have the date in $date variable. Let's create the template.


$emailBody = "
	<html>
	<head>
		<title>$email is contacting you</title>
	</head>
	<body style=\"background-color:#fafafa;\">
		<div style=\"padding:20px;\">
			Date: <span style=\"color:#888\">$date</span>
			<br>
			Email: <span style=\"color:#888\">$email</span>
			<br>
			Message: <div style=\"color:#888\">$message</div>
		</div>
	</body>
	</html>
";


4. Sending the email

In emails, settings headers are really important.


$headers = 	"From: Contact Form <[email protected]>" . "\r\n" .
			"Reply-To: $email" . "\r\n" .
			"MIME-Version: 1.0\r\n" . 
			"Content-Type: text/html; charset=iso-8859-1\n";


FROM header is not so important in this case. Use anything you need. REPLY-TO header should always be set to the user's email. Last two headers say that it is an HTML email.

Now we can send the email. If the mail was sent successfully we set $sent variable to true to use later.


$to = '[email protected]';
$subject = 'Contacting you';

if (mail($to, $subject, $emailBody, $headers)) {
	$sent = true;	
}

5. Reporting errors

We have two variables ($emailError and $messageError) which save error messages on failure. Let's add a code to display the error if exists. Add this code to the bottom of your page (before the </body> tag). To learn more about how to use PHP in HTML please refer to this tutorial.


<?php if (isset($emailError) || isset($messageError)) : ?> 

	<div id="error-message">
			
		<?php 
			echo isset($emailError) ? $emailError . '<br>' : ''; 
			echo isset($messageError) ? $messageError . '<br>' : ''; 
		?>

	</div>


<?php endif; ?>


Finally, we can add code to show the user a message that his data was submitted successfully.


<?php if ($sent === true) : ?> 
	<div id="done-message">
		Your data was succesfully submitted
	</div>
<?php endif; ?>



Styling the Form

Everyone likes beautiful websites. This is an example that how you can style your form. You can improve this according to your ideas. This is the CSS code I have used.


body {
	background-color:#fafafa;
}
form {
	width:50%;
	margin:auto;
}
.input-wrap {
	padding:20px 0;
}
.label {
	display:block;
	margin-bottom:2px;
}
input, textarea {
	border:1px solid #eee;
	padding:6px;
	border-radius:3px;
	width:100%;
}
textarea {
	height:200px;
	resize:none;
}
.submit-button {
	padding:10px;
}


The Final Code


<?php
if ($_SERVER['REQUEST_METHOD'] === "POST") {
	if (empty($_POST['email'])) {
		$emailError = 'Email is empty';
	} else {
		$email = $_POST['email'];

		// validating the email
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$emailError = 'Invalid email';
		}
	}
	if (empty($_POST['message'])) {
		$messageError = 'Message is empty';
	} else {
		$message = $_POST['message'];
	}
	if (empty($emailError) && empty($messageError)) {
		$date = date('j, F Y h:i A');

		$emailBody = "
			<html>
			<head>
				<title>$email is contacting you</title>
			</head>
			<body style=\"background-color:#fafafa;\">
				<div style=\"padding:20px;\">
					Date: <span style=\"color:#888\">$date</span>
					<br>
					Email: <span style=\"color:#888\">$email</span>
					<br>
					Message: <div style=\"color:#888\">$message</div>
				</div>
			</body>
			</html>
		";

		$headers = 	'From: Contact Form <[email protected]>' . "\r\n" .
    				"Reply-To: $email" . "\r\n" .
    				"MIME-Version: 1.0\r\n" . 
					"Content-Type: text/html; charset=iso-8859-1\r\n";

		$to = '[email protected]';
		$subject = 'Contacting you';

		if (mail($to, $subject, $emailBody, $headers)) {
			$sent = true;	
		}
	}
}
?>
<html>
<head>
	<title>PHP Contact Form - Email Method - Hyvor Developer</title>
	<style type="text/css">
		
		body {
			background-color:#fafafa;
		}
		form {
			width:50%;
			margin:auto;
		}
		.input-wrap {
			padding:20px 0;
		}
		.label {
			display:block;
			margin-bottom:2px;
		}
		input, textarea {
			border:1px solid #eee;
			padding:6px;
			border-radius:3px;
			width:100%;
		}
		textarea {
			height:200px;
			resize:none;
		}
		.submit-button {
			padding:10px;
		}
	</style>

</head>
<body>

<form method="POST" action=""> 
	<div class="input-wrap">
		<span class="label">Email:</span>
		<input type="text" name="email">
	</div>
	
	<div class="input-wrap">
		<span class="label">Message:</span>
		<textarea name="message"></textarea>
	</div>

	<div class="input-wrap">
		<input type="submit" name="submit" value="Submit" class="submit-button">
	</div>
</form>

<?php if (isset($emailError) || isset($messageError)) : ?> 
	<div id="error-message">
		<?php 
			echo isset($emailError) ? $emailError . '<br>' : ''; 
			echo isset($messageError) ? $messageError . '<br>' : ''; 
		?>
	</div>
<?php endif; ?>


<?php if (isset($sent) && $sent === true) : ?> 
	<div id="done-message">
		Your data was succesfully submitted
	</div>
<?php endif; ?>

</body>
</html>



Author SupunKavinda