Email form contents with PHP

by CarcaBot on July 24, 2009 · 0 comments

Do you want to include a contact form on your website, but you don't know how to get the form information emailed to you? Well rather than using 3rd party components, you can easily use this PHP snippet to parse and email form contentst to the site administrator.

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$body = $_POST['body'];

// check for valid input
if ($name != "" AND $email != "" AND $body != "") {

  $sendto = "admin@yoursite.com"; //change to your email address obviously
  $subject = "Inquiry from yoursite.com";
  $message = "This is a message from your site:
                   From: $name
                   Email: $email
                   Message: $body"
;
  // send
  mail("$sendto", "$subject", "$message");
  echo "Your message was sent";
}
?>

and here's the simple html to generate the form

<form method="post" name="mailform" action="<?=$_SERVER['PHP_SELF'] ?>">
 
<table width="200"  border="0" cellspacing="0">
  <tr>
    <td width="62">Name:</td>
    <td width="134">
      <input name="name" type="text" id="name">
   </td>
  </tr>
  <tr>
    <td>Email:</td>
    <td><input name="email" type="text" id="email"></td>
  </tr>
  <tr>
    <td valign="top">Message:</td>
    <td><textarea name="body" cols="45" rows="10"></textarea></td>
  </tr>
</table>
  <br>
  <input type="submit" name="Submit" value="Submit">
  <input type="reset" name="Submit2" value="Reset">
</form>

Previous post:

Next post: