How to use basic PHP mail() function code to send emails from a form

September 12, 2017     0 comments

You can use the PHP mail() function to send an email with PHP. The simplest way to do this is to send a text email. This is one way to handle the results when a visitor to your website fills out a form.

Basic PHP email() function code

Below is the code for the basic email function. You can take the script and actually use a form on your website to set the variables in the script above to send an email.

<?php
//if "email" variable is filled out, send email
  if (isset($_REQUEST['email']))  {
  
  //Email information
  $admin_email = "someone@example.com";
  $email = $_REQUEST['email'];
  $subject = $_REQUEST['subject'];
  $comment = $_REQUEST['comment'];
  
  //send email
  mail($admin_email, "$subject", $comment, "From:" . $email);
  
  //Email response
  echo "Thank you for contacting us!";
  }
  
  //if "email" variable is not filled out, display the form
  else  {
?>

 <form method="post">
  Email: <input name="email" type="text" /><br />
  Subject: <input name="subject" type="text" /><br />
  Message:<br />
  <textarea name="comment" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
  </form>
  
<?php
  }
?>

So let’s now review what the form is actually doing.

  1. The first part checks to make sure the email input field is filled out. If it is not, then it will display the HTML form on the page. If the email is in fact, set (after the visitor fills out the form), it is ready to send.
  2. When the submit button is pressed, after the form is filled out, the page reloads and reads that the email input is set, so it sends the email.

Keep in mind that this is a basic tutorial to explain how to use the mail() function in PHP. Using the method, exactly the way it is can be insecure and should not be used on your website. This tutorial is aiming to provide you the basic of how to use phpmail() and for further use, you may want to look into securing your code to possible hacks.

If this is your first time setting up php mail() function, we recommend reading the official documentation on using this code as it also includes examples.


How helpful was this article to you?

Leave a comment

Your name
Your email address
Comment on this article