PHP form to email explained

It is a common requirement to have a form on almost any web site.

In this article, we will create a PHP script that will send an email when a web form is submitted.

There are two parts for the web form:

  1. The HTML form code for the form. The HTML code below displays a standard form in the web browser. If you are new to HTML coding, please see: HTML form tutorial
  2. The PHP script for handling the form submission. The script receives the form submission and sends an email.


HTML code for the email form:

<form method="post" name="myemailform" action="form-to-email.php">

Enter Name:	<input type="text" name="name">

Enter Email Address:	<input type="text" name="email">

Enter Message:	<textarea name="message"></textarea>

<input type="submit" value="Send Form">
</form>

The form contains the following fields:
name, email and message.

name and email are single-line text input fields where as message is a text area field (multi-line text input).

You can have different types of input fields in a form. Please see the HTML form input examples page for details.

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.

<?php
  $name = $_POST['name'];
  $visitor_email = $_POST['email'];
  $message = $_POST['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."

Sending the email

The PHP function to send email is mail().

mail(to,subject,message,headers)

For more details, see the PHP mail() page.

The headers parameter is to provide additional mail parameters ( like the from address, CC, BCC etc)

Here is the code to send the email:

<?php

  $to = "yourname@yourwebsite.com";

  $headers = "From: $email_from \r\n";

  $headers .= "Reply-To: $visitor_email \r\n";

  mail($to,$email_subject,$email_body,$headers);

 ?>

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.

<?php
  $to = "name1@website-name.com, name2@website-name.com,name3@website-name.com";

  mail($to,$email_subject,$email_body,$headers);
?>

You can use the CC (carbon copy) and BCC (Blind Carbon Copy) parameters as well. The CC and BCC emails are added in the ‘headers’ parameter.

Sample code:

<?php
$to = "name1@website-name.com, name2@website-name.com,name3@website-name.com";

$headers = "From: $email_from \r\n";

$headers .= "Reply-To: $visitor_email \r\n";

$headers .= "Cc: someone@domain.com \r\n";

$headers .= "Bcc: someoneelse@domain.com \r\n";

mail($to,$email_subject,$email_body,$headers);
?>

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.

Here is the updated code:

<?php
function IsInjected($str)
{
    $injections = array('(\n+)',
           '(\r+)',
           '(\t+)',
           '(%0A+)',
           '(%0D+)',
           '(%08+)',
           '(%09+)'
           );
               
    $inject = join('|', $injections);
    $inject = "/$inject/i";
    
    if(preg_match($inject,$str))
    {
      return true;
    }
    else
    {
      return false;
    }
}

if(IsInjected($visitor_email))
{
    echo "Bad email value!";
    exit;
}
?>

In general, any value used in the header should be validated using the code above.

Better, complete validations could be done using the PHP form validation script here.

PHP form to email complete code

The link below contains the complete form, validation and emailing code.

Download the PHP form to email code

Comments on this entry are closed.

  • My program is executing but i did not get mail to my id,
    Is any setting required in php.ini file
    do let me know ASAP

  • Hi There,

    I have my entire form functioning correctly, however the message that I would like to be sent needs to be changed to an HTML email. I keep getting a syntax error? The HTML coding my designer sent over to me keeps triggering a syntax error. However when I just use text without any embedded URLs, etc.. I receive no error.

    What do I need to omit from his coding in order to put this in the form…

  • How do I add a “thank you” note in the CC to the sender’s email as well? Example: Dear $email_from, below is your enquiry. We will keep in touch with you asap. Thanks.

  • This just does not work as advertised. Another typical web tutorial that misses a step, so it’s useless.

    • Tutorial can show only the coding steps. It runs on your webserver, that has it’s own configuration. The script should be updated correct for your needs.
      Why is my PHP script not sending emails?

  • In the section:
    “Securing the form against email injection”
    Does the code snippet go before or after the header parameters?

    Thank you.

  • Thank your post.

    I like this way to send email by php;

  • How do you display the form field contents to a thank you page after you send the email?

  • how to post comments in web like this

  • Hi, I’ve tried your script but am unable to rec any messages. I check my mail server and there are no emails pending.

    could you take a look. I used yours, wwww.yetiphoto.ca/form-to-email.php and your thank you and form-page.html. I also edited it to my http://www.yetiphoto.ca/call-new-3. php and call-new-4.php.

    I also included your js in script for varification.

    I would really appreciate your assistance is getting my call-new?.php to work.

    Thanks

    David Jennings

  • I am updating my site to include a form, but the form-to-mail script is my headache

  • its very very useful,,,thankz for the code.

  • I need php code the will send an email directly form the site without going through the local email client

  • Dreamweaver CS5 Classroom in a book brought me here ^_^

  • Great codem no doubt but had anyone out there managed to get rid of the e-mail link we get on the bottom of the e-mail message we receive?

    I don0t really need my own e-mail on the e-mail message…

    Thanks!

    • There is a period (.) at the end of the $email_body variable outside of the semi colon and before the $to variable that strings together the message and the email that it sends it to. Just delete that period.

      • $email_body = “You have received a new message from the user $name.\n”.
        “Here is the message:\n $message”. <this period should be changed to a semi colon

        $to = "blah@blah.com";

  • Great code! The best e-mail/feedback form I’ve came across with but…

    Is there a way to remove our own e-mail address at the end of the message we receive? What’s the point of that?

    Thanks!

  • Hi

    I’m sorry to insist but it seems my comments have been deleted.
    As far as I could figure out with the little I know of PHP, sending out the $email_body with the $message is also writing my own e-mail address (destination e-mail) in the message body.

    Now, since I am using this as a feedback message to my site and not as an auto-reply, how can I remove it (just as a design thing)? I don’t really need to know my own e-mail address as a different user would.

    Thanks!
    (maybe you could reply by e-mail….)

  • thank you for written above php code for email

  • Thanks for the code. Got it to work great. Just wondering if it is possible to add formatting to the text like headings and also add a company logo?

  • Everything worked but I need one change. I don’t want the e-mail to show it came from me. I want it to have the submitter’s e-mail in the from. I have tried putting $email instead of my email address but it just shows it is from $email instead of the value of $email. Any ideas?

  • I used the form-to-email.php file to make a form for a clients site. I have it set up w/ a text area for visitors to make suggestions for his blog. It seems though that people are either just clicking submit w/o adding any suggestion. Or …this is my question: is it possible something (like a refresh?) is causing it to automatically run. My client is getting emails that are blank. Is there an error on the server that can cause the form-to-email.php file to behave on its own? I’ve tested it w/ actual text and it works fine every time.
    Thanks!