On hitting the submit button, the form will be submitted to “form-to-email.php”. This form is submitted through the POST method

Accessing the form submission data in the PHP script

Once your website visitor has submitted the form, the browser sends the form submission data to the script mentioned in the ‘action’ attribute of the form. (for the current form, the script is form-to-email.php)

Since we have the form submission method mentioned as POST in the form (method=’post’) we can access the form submission data through the $_POST[] array in the PHP script.

The following code gets the values submitted for the fields: name, email and message.

Composing the email message

Now, we can use the above PHP variables to compose an email message. Here is the code:

<?php
$email_from = 'yourname@yourwebsite.com';
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message".
?>

The ‘From’ address, the subject and the body of the email message are composed in the code above. Note the way the body of the message is composed using the variables.

If a visitor ‘Anthony’ submits the form, the email message will look like this:
"You have received a new message from the user Anthony.
Here is the message:
Hi,
Thanks for your great site. I love your site. Thanks and Bye.
Anthony."

Notice that we put your email address in the ‘From’ parameter and the visitor’s email address in the ‘Reply-To’ parameter. The ‘From’ parameter should indicate the origin of the email. If you put the visitor’s email address in the ‘From’ parameter, some email servers might reject the email thinking that you are impersonating someone.

Sending the email to more than one recipients

If you want to send the email to more than one recipients, then you just need to add these in the “$to” variable.

Securing the form against email injection

Spammers are looking for exploitable email forms to send spam emails. They use the form handler script as a ‘relay’. What they do is to submit the form with manipulated form values. To secure our form from such attacks, we need to validate the submitted form data.

All the values that go in the ‘headers‘ parameter should be checked to see whether it contains \r or \n. The hackers insert these characters and add their own code to fool the function.

Hi, Thanks a lot for this! This is my first ever php project. Is there a way to test using MAMP? …I guess, I should say, I tested it in MAMP and didn’t receive any emails. Do I need to have it on a real server to get emails to go through?