Sending email with PHP

Hello and welcome to my tutorial! In this tutorial we will create a simple mailing system with PHP so users can send email through your website. We will include protection like checking for blank fields and making sure that the user email address is valid.

Create the form

First thing we want to do is to create the form. This is where the visitors of your website will be using to send you um email.

  <form name="contact" method="post" action="contactprocess.php">
    <input type="text" name="ename" size="30"><br/>

    <input type="text" name="eemail" size="30"><br/>
    <input type="text" name="esubject" size="30"><br/>

    <textarea name="emessage" cols="30" rows="10"></textarea><br/>
    <input type="submit" name="esubmit" value="Send Mail" style="cursor:pointer">
    <input type="hidden" name="eip" value="<?php echo $_SERVER["REMOTE_ADDR"]; ?>">

Save the code above as contact.php. If you copy and pasted the above code your form should look like this. Dont worry about the looks right now you can edit that later!

Breaking down the form

We have the following information on our form:
Name - Users name or nickname.
Email - Users email, this is where the reply will me mailed.
Subject - Subject of the mail.
Message - Message or body.
We also have an hidden input which return the users IP address, this could be useful for email abuse.

Mail Processing

Below is the code which will be trigger when the users hit the "Send Mail" button on the above form. Make sure you change the $mymail variable value to your actual email address.


  //Some variables
  $mymail = "";
  $ename = $_POST['ename'];
  $eemail = $_POST['eemail'];
  $esubject = $_POST['esubject'];
  $emessage = $_POST['emessage'];
  $eip = $_POST['eip'];

  //Function to check email address
  function checkemail($eemail) { 
    if(eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$",$eemail))  { 
      return true; 
    else { 
      return false; 

  //Mail Processing
  if ($_POST['esubmit']) {
    //Check for blank fields
    if ($ename == "" || $eemail == "" || $esubject == "" || $emessage == "") {
      echo "<p>It appears that you left a blank field.<br/> Please make sure you fill everything in.</p>";
    //Check to see if the email address is valid
    else if (checkemail($eemail) == false) { 
       echo "<p>It appears that you enter an invalid email address.<br/> Please check your email again.</p>";
    //Send the email if there's no error
    else {
      $body = "$emessage\n\nName: $ename\nEmail: $eemail\nIp: $eip";
      mail($mymail,$esubject,$body,"From: $eemail\n");
      echo "<p>Thank you for your email $ename!</p>";


Save the code above as contactprocess.php. If your using a different file name make sure you also change the action path on your form.

Print this page | Discuss this tutorial

Next »

Home | Site Map | Privacy Policy | Advertising | Contact Us
Copyright © 2006-2014 - All Rights Reserved.
eXTReMe Tracker