x
^

How to create a dynamic mail script in PHP

August 8, 2014

Section 1: The HTML

So there are a million form scripts available on the web and some are bad and difficult but on the flip side some are easy and very versatile. But today I’m going to show you how to create your own dynamic PHP email script that will be easy to configure without touching a line of PHP after it’s written
. You’ll be able to set all of the setting via HTML hidden fields. If you’re not confident in PHP but you are in HTML then simply have a read and just download the script at the bottom of this page.  You can utilise it straight away. So lets begin.

NOTE: if you don’t know PHP very well, you may want to read up about the basics, if not you can skip to the bottom of this article and download the files and just do section one of this tutorial.

Okay first we’re going to start with writing the basic HTML form so we can start testing straight away. Simple open up some form tags and send the action of the form to “mail_action.php” and make sure you use the method “POST” to keep all of our information hidden whilst sending to the script. It can also handle a lot more data and characters than the GET method. Once you’ve got that down, simply throw in a submit button and the form fields you want. We’re also going to add some hidden fields in there to set values like the email, subject, email top & bottom, reply email and success/failure URLs. Like so:

<form action="mail_action.php" method="post">

    <!--Hidden data-->
    <input type="hidden" name="email_address" value="jason@example.com" />
    <input type="hidden" name="email_subject" value="Hello World" />
    <input type="hidden" name="email_top" value="This is the top of the email." />
    <input type="hidden" name="email_bottom" value="This is the bottom of the email" />
    <input type="hidden" name="reply_email" value="no-reply@example.com" />
    <input type="hidden" name="success_url" value="http://www.google.com" />
    <input type="hidden" name="error_url" value="http://www.youtube.com" />

    <input type="submit">

</form>

Now we’re going to want to add fields that the user can see, otherwise this form is pretty pointless! This is where it gets interesting. We’re going to submit the values to the PHP mail script as an array which we can pull apart and configure into an email later. So all you need to do is set the name of the field to “form_data[FIELDNAME]”. Which will then take the value and assign it to that name. Here’s an examples:

<input name="form_data[Name]" placeholder="Name">
<input name="form_data[Email]" placeholder="Email">    
<input name="form_data[Subject]" placeholder="Subject">

So wait, why do we have to do this? Well because it’ll allow us to assign the field values a name so we know what the hell is going on. In this example, the name field will appear in an email like so (when they submit the value of Jason in the field).

Name: Jason

Easy stuff! So now all together your form should look like this:

<form action="mail_action.php" method="post">

    <!--Hidden data-->
    <input type="hidden" name="email_address" value="jason@examples.com" />
    <input type="hidden" name="email_subject" value="Hello World" />
    <input type="hidden" name="email_top" value="This is the top of the email." />
    <input type="hidden" name="email_bottom" value="This is the bottom of the email" />
    <input type="hidden" name="reply_email" value="no-reply@example.com" />
    <input type="hidden" name="success_url" value="http://www.google.com" />
    <input type="hidden" name="error_url" value="http://www.youtube.com" />
    
    <!--To change the text before the value submitted change the text [] (No spaces allowed). 
    Example: form_data[Name] will display in the email like: "Name: Value submitted from form"-->
     <input name="form_data[Name]" placeholder="Name">
     <input name="form_data[Email]" placeholder="Email">    
     <input name="form_data[Subject]" placeholder="Subject">
         
    <input type="submit">

</form>

Section 2: The PHP

So here comes the fun and creative part, the PHP. First things first, create your PHP document and name it “mail_action.php”.

Once you’ve done that, lets start by with a little house keeping. First make sure you’ve saved the mail_action.php in the same folder as your HTML document, now if you haven’t that’s fine; just make sure you point the forms action to the correct directory. Secondly, if you don’t have output buffering set automatically on in your PHP (majority of servers don’t by default), remember to use “ob_start();” on first line of your PHP document. This will allow us to use the header function for a redirect.

Okay now that’s out of the way, lets start. (I’ll be using ob_start).

So lets grab those values from the form and assign them to variables.

<?php ob_start();
//Grabbing Settings
$success_url = $_POST["success_url"];
$error_url = $_POST["error_url"];
$reply_email = $_POST["reply_email"];

//Grabbing hidden field data.
$email = $_POST["email_address"];
$subject = $_POST["email_subject"];
?>

Next, we’ll need to set the email headers so the email clients know what the hell is going on! So basically lets apply these to a $header variable which we can pass into the mail function later on. We’ll also be using the variables we made a second ago (originally pulled from the hidden fields).

$headers = 'From: '. $reply_email . "\r\n" .
           'Reply-To:' . $reply_email . "\r\n" .
           'X-Mailer: PHP/' . phpversion();

Nice and easy so far don’t you think? Now lets start constructing the email’s body of content and play about with the values submitted by the user. How we’re going to do it this is by assigning the entire message to a variable called ‘$message’, but to get the content from the email we’ll be running a foreach loop to keep everything easy and dynamic on the front end. Now remember on the form we used form_data[value], well that was putting everything the user submitted into a lovely little array for us to utilise.

The foreach loop is going to get the value of each form_data array item and the assigned key, which is the value you put in the HTML form earlier. For example: form_data[name] would come across to PHP in the array with the assigned value of “Jason”(depending on what the user enters into the field before pressing submit). Now PHP will see this array like this: form_data(‘name’ => ‘Jason’) and for each form_data item it’ll add more to the array, like so: form_data(‘name’=>’Jason’, ‘email’=>’jason@example.com’, ‘phone’=>’078912345678′).

Our foreach loop is going to split those values and assign them to variables that let us shape them how we want. I’ll be shaping them up like so:

Name: Jason
Email: jason@example.com
Phone: 078912345678

We’ll also be using the before and after form values before and after the foreach loop. So here’s the code for that. Have a good loop and try and understand what’s going on.

//Initalize Message Variable
$message = ""; 

//The Email:
    //Top of email text
    $message .= $_POST["email_top"];
    $message .= "\r\n";
    $message .= "\r\n";
    
    $form_data = $_POST['form_data'];
    
    //The form going into email
    foreach($form_data as $form_header => $form_data){
        
        //Asigning the message fields to $message variable.
        $message .= $form_header.": ".$form_data;
        
        //The spaces inbetweeen
        $message .= "\r\n";
    }
    
    //Bottom of the email
    $message .= "\r\n";
    $message .= "\r\n";
    $message .= $_POST["email_bottom"];

Now all we need to do is use all of our assigned variables and mail them out to the desired email. For this we’ll be using the mail() function in PHP. You can find more information on this here: PHP mail() function. On success of the mail function we’ll simple redirect the user to the page we desire (set in the HTML form). And if it doesn’t work for any reason, we can send them to our desired error page to give the user further instructions. And if you forget to set a value for the error message, we’ll give a simple error message (you can change this). The header function is what we’ll use to redirect and this is why I asked you to make sure you use ob_start() at the beginning of the PHP document.

//Check if email is successfully sent
if(mail ($email, $subject, $message, $headers)){
    header("location: {$success_url}");
    } else {
        if(isset($_POST["error_url"])){//user set error url
            header("location: {$error_url}");
        } else { //Default error message
            echo "The message was not sent. An error has occured. Please try again later.";}
        }

And putting it all together would look something like this. Feel free to copy this in and edit until your hearts content. I believe playing is the best way to learn!

<?php ob_start();
//Grabbing Settings
$success_url = $_POST["success_url"];
$error_url = $_POST["error_url"];
$reply_email = $_POST["reply_email"];

//Grabbing hidden field data.
$email = $_POST["email_address"];
$subject = $_POST["email_subject"];
$headers = 'From: '. $reply_email . "\r\n" .
            'Reply-To:' . $reply_email . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
        
//Initalize Message Variable
$message = ""; 

//The Email:
    //Top of email text
    $message .= $_POST["email_top"];
    $message .= "\r\n";
    $message .= "\r\n";
    
    $form_data = $_POST['form_data'];
    
    //The form going into email
    foreach($form_data as $form_header => $form_data){
        
        //Asigning the message fields to $message variable.
        $message .= $form_header.": ".$form_data;
        
        //The spaces inbetweeen
        $message .= "\r\n";
    }
    
    //Bottom of the email
    $message .= "\r\n";
    $message .= "\r\n";
    $message .= $_POST["email_bottom"];

//Check if email is successfully sent
if(mail ($email, $subject, $message, $headers)){
    header("location: {$success_url}");
    } else {
        if(isset($_POST["error_url"])){//user set error url
            header("location: {$error_url}");
        } else { //Default error message
            echo "The message was not sent. An error has occured. Please try again later.";}
        }
?>

I hope you’ve learnt something today, I’ve tried my best to keep this tutorial simple and easy to understand. Remember you can download the entire project below to use and tweak until you’re happy with it. You can see we’ve made this form dynamic which will make the script easier to utilise in future. You’ll hardly have to edit the script once created because all of the settings are available in the HTML form via hidden fields.

DOWNLOAD PROJECT

Leave a Reply

Work With Me