Sending email with PHP
Breaking it down

The function below will check if the user entered a valid 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; 
    } 
  }

I will not go into details with regular expression but basically it will check if the email address is in the following format: email@address.com. I would like to thank Loon former owner of netcode.net for this function.

if ($_POST['esubmit']) {
  if ($ename == "" || $eemail == "" || $esubject == "" || $emessage == "") {
    echo "<p>It appears that you left a blank field.<br/> Please make sure you fill everything in.</p>";
  }
  elseif (checkemail($eemail) == false) { 
    echo "<p>It appears that you enter an invalid email address.<br/> Please check your email again.</p>";
  }

The above code will check for errors. If there's a blank field or the email address is not valid using our checkmail() function then an error will be printed out.

PHP's mail() function

If we dont get any errors then the code below will be triggered!

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>";
}

That will send at an email with the user name, email address, subject and of course his/her message!

Our mail function is in the current format: mail(<recipient_email_address>,<subject>,<body>,<sender_email_address>);

The end

Well thats about it for this tutorial. Remember this is the very basic for sending mail with PHP. I suggest reading through PHP documentation if you want to learn more, click here.


Print this page | Discuss this tutorial

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