OrangeWeb.

A Little Bit of Orange Never Hurt Anyone

Quick Automatic PHP Mailer

05 Jun 2009

I am not a web developer, nor do I pretend to be, but as a web designer I do like to dabble. I have built up quite a range of useful scripts that I have written and I continually use over and again.

A very useful and simple script, commonly used by myself, is an automatic PHP mailer using a FOREACH loop to get all the POST data. This method is quick and easy to implement.

Why should I use a FOREACH loop in a PHP mailer?

The answer is simple, this script enables you to get all the field names and values from a form automatically. Lets have a look what I mean..

simple-formA very simple form using only 3 text fields

If I was to email the form results using PHP, on my confirm page I would have code very similar to the following…

Code:
<?php
$to = “test@thisisatestemail.com.au”;
$from = “no-reply@thisisatestemail.com.au”;
$subject = “This is my subject”;

$message = “Name: ” . $_POST['fname'] . “\n”;
$message .= “Last Name: ” . $_POST['lname'] . “\n”;
$message .= “Email: ” . $_POST['email'];

$headers = “From: $from”;

mail($to, $subject, $message, $headers)
?>

Now, don’t get me wrong, this works great, and you do have ultimate control over what fields are displayed and how. But imagine a form with say 30+ fields? You don’t want to have to append the field name to the message 30+ times. For 3 immediate reasons:

1. It can be a complete waste of time
2. As there is more code, the chances for a syntax error greatly increase
3. It is repetitive and boring to write

The easiest way around it is to create a FOREACH loop for all the values in POST. An example of said code is as follows:

Code:
$to = “test@thisisatestemail.com.au”;
$from = “no-reply@thisisatestemail.com.au”;
$subject = “This is my subject”;
$message       = “”;
$headers       = “From: $from\r\n”;
//This is the loop that grabs POST values and adds them to the variable
foreach($_POST AS $field => $value) {
$message    .= $field . “: ” . $value .”\r\n”;
}
mail($to, $subject, $message, $headers);

Basically this code grabs all the fields and values in POST and appends them to the variable $message, which is then mailed. You can take it a little bit further and exclude certain fields that you do not want to see in your email, such as the submit button.

You can download a working form using this PHP mailer here.

Posted by Michael Raffaele in PHP, Tutorials, Website Development | Permalink