Saturday 8 December 2012

Send Emails Using PHP

How to Send Emails Using PHP

Hi everyone, I am not sure if anyone is interested in this, but I know I was when I first started to learn about PHP so I thought I would write a tutorial on how to send an email message through a PHP script. Once you know how to do this, it is simple to setup and you can do some cool things with it once you first grasp the basics of how everything works. So let's get started.

The Basics:

Every email has 4 basic components.

  • To: the email address of the person the email is being sent to
  • From: the email address of who the email is coming from
  • Subject: the subject of the email being sent
  • Message: the body of the email


Those 4 basic components are the heart of the PHP script that sends the email. Each one of those 4 components will be assigned to a variable in the PHP script and will be used to send the email. So to get started, we will need to create a new .php document. Whatever program you are using such as Dreamweaver (that is what I am using), TextMate, NotePad, Wordpad, BBEdit, or any other program you are using, copy and paste the following code at the top of the new .php document.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create Email</title>
</head>
<body>


Once you have got that pasted into your new document, you want to go ahead and open your PHP tags. So right under the code you just pasted, type this:

<?php


Now this is where the fun starts. Instead of using the normal approach of creating the HTML page that will then send the POST data to the PHP page and then validate all of the user input that way, I decided to take a different approach. The way that I am going to show you is not hard at all, and you may already know it. If you do not know it already, it may seem harder if you have never seen it before, but once you learn this way of combining the HTML form and PHP script into one document instead of 2 documents your code will be more portable, easier to fix and find bugs, easier to improve, and overall just a better approach in my opinion. But there are sometimes where this approach is not the best or not possible and you must separate the HTML from the PHP. If you have no idea what I am talking about, you will in a few seconds :D

Okay, so once you have your opening PHP tag typed in, you need to check to see if the script has been submitted. So you would type this:

//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {


What that checks for is the hidden form input in the HTML form. It checks to see if it "is set". The isset() function returns true as long as the variable exists and is not NULL. So, in this case, if the user filled out the form correctly, the $_POST['submitted'] variable is assigned the value "true" and the script continues along checking to see if any other errors occurred.

Next, once the script gets past the $_POST['submitted'] variable, it sets up an $errors array.

//Create an array that will contain all of the errors if ant are to occur once the script runs
$errors = array() ;


The $errors array will contain and hold all of the errors that occur (if any do occur) during the run of the script. Once you see the rest of the script, this will make more since to you.

Validation of User Input:

Next, is one of the most important parts of the script. User input validation checks. Although this is not the most secure way of securing the PHP script and checking for spam attacks and other attacks (I will write another tutorial on this later on), this works great and gets the job done for way more than the average person. To do our 1st validation check of 4, type this:

//Validate all user input
if (!empty($_POST['to'])) {
        $to = trim(strip_tags($_POST['to'])) ;
} else {
        $errors[] = 'You must enter a <b>to</b> address.' ;
}


What this does is that it first checks to make sure that the variable $_POST['to'] IS NOT empty. If it IS NOT empty, which means that it is not equal to 0 (0 as an integer), "0" (0 as a string), "" (an empty string), NULL, FALSE, array() (an empty array). So as long as the input by the user is not equal to the list of things above, the $_POST['to'] variable will be assigned to the variable $to. IF the $_POST['to'] variable is empty, it will NOT be assigned to the $to variable and an error message will be assigned to the $errors array. The code

$errors[] = 'You must enter a <b>to</b> address.' ;


means to assign the next numerical index to the $errors array. So, for example, if you have an array setup like this:

$array = array(1 => 'Value 1', 2 => 'Value 2', 3 => 'Value 3') ;


and you want to add a value to this, all you have to do is type the following code:

$array[] = 'Value 4' ;


Your new $array will now look like this:

$array = array(1 => 'Value 1', 2 => 'Value 2', 3 => 'Value 3', 4 => 'Value 4') ;


So that is what we are doing in our email example with the $errors array. Every time an error occurs in the script, instead of having to kill the script with the exit() function or die() function calls, you can allow the script to continue so the user will be able to see all of the errors that occur in the script rather than the last one that occurred.

So we want to do this same thing for each of the 4 basic components. Our whole script so far should look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create Email</title>
</head>
<body>
<?php
//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {
        
        //Create an array that will contain all of the errors if ant are to occur once the script runs
        $errors = array() ;
        
        //Validate all user input
        if (!empty($_POST['to'])) {
                $to = trim(strip_tags($_POST['to'])) ;
        } else {
                $errors[] = 'You must enter a <b>to</b> address.' ;
        }
        
        if (!empty($_POST['from'])) {
                $from = "From: {$_POST['from']}" ;
                trim(strip_tags($from)) ;
        } else {
                $errors[] = 'You must enter a <b>from</b> address.' ;
        }
        
        if (!empty($_POST['subject'])) {
                $subject = trim(strip_tags($_POST['subject'])) ;
        } else {
                $errors[] = 'You must enter a <b>subject</b>.' ;
        }
        
        if (!empty($_POST['message']) && $_POST['message'] != 'Enter Your Message Here...') {
                $message = trim(strip_tags($_POST['message'])) ;
        } else {
                $errors[] = 'You must enter an original <b>message</b>.' ;
        }


All of the validation methods are the same foreach component of the email except for the $_POST['message'] variable. You might have noticed that it has an extra little bit of validation along with it. I will explain that part a little bit later.

Checking For Errors:

Next, we need to check to see if there were any errors when the user submitted the script. To do this, just type the following line of code:

//Check to make sure there were no errors while running the script
        if (empty($errors)) {


This line of code makes sure that the array $errors is empty. If the $errors array is empty, then there were no errors so far and now we are going to send the email :D

Sending the Email:

Since there are no errors in the script so far, it's now safe to try and send the email. To send the email, it is really simple. You will need to use the mail() function which can take up to 5 arguments. You will most likely only use 4 of them like I did here is this script. The 5 arguments the mail function can take are the following:

  • To: the message the email is being sent to
  • Subject: the subject of the email
  • Message: the actual message of the email
  • Additional Headers: these consist of headers such as from, cc, bcc, etc.
  • Additional Parameters: such as sending email in html or with sending email with attatchments


So the mail() function can look something like this:

mail('three3211@gmail.com', 'Subject Goes Here', 'Message of the Email Goes Here', 'From: somebody@domain.com') ;


Please take notice of a couple of things here.

  • Everything must be in quotes unless it is a variable
  • The From header is required and must be written like we here.


With that in mind, here is the code on how to send the email:

//Create the email and mail
if (mail($to , $subject , $message , $from)) {
        echo '<p>Your email has been sent!</p>' ;
} else {
        echo '<p>There was an error sending your email, please try again.</p>' ;
}


This checks to make sure that the email has been sent by putting it in an IF statement. We used the variable names here for each of the arguments that the mail function needs. Whatever the user types in the form will be replaced here when the form has been submitted. If the mail() function returns true, it will print out to the browser "Your email has been sent!". To make things clear, there is NO way of telling if the person you send the email to actually receives the email, reads the email, or if the email was actually even sent. The only way to test is to run the code through different functions and test and test it against your own email account to make sure it works. I have checked this against my Gmail and Yahoo email accounts and they both work great and instantly and they do NOT go to the spam folder. They go straight to my inbox.

Now, I am not going to go into details on this, but we now need to add an else clause just in case there were any errors when the form was submitted. The code for this would be this:

} else {
        //There were errors in the submission
//Use a foreach loop to loop through the errors array
//Print out errors heading before foreach loop

echo '<h2>Errors</h2>' ;
                
        foreach ($errors as $msg) {
                echo "- $msg<br />" ;
        }
                } //End of else clause


Display the HTML Form

Next, we need to add another else clause just in case the form has not been submitted. For example, if you were to go to the webpage for the first time, the HTML form would not submitted, and you would have to fill it out. So in that case we need to display the form for all of our first time visitors and for everyone else who wants to resubmit the form again. To do this, we need to add an else clause that will belong to the IF statement we made at the very beginning of the script which was:

//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {


Now we are adding an else clause to this. So we would add this line of code to the bottom of our script:

} else { 
//The script has not been submitted yet
//Display the HTML form
echo '<form action="mail.php" method="post">
          <fieldset><legend>Enter your information in the form below:</legend>
          <p>To: <input name="to" type="text" size="30" /></p>
          <p>From: <input name="from" type="text" size="30" /></p>
          <p>Subject: <input name="subject" type="text" size="30" /></p>
          <p>Message:</p> <p><textarea name="message" cols="50" rows="10">Enter Your Message Here...</textarea></p>
          <input name="submit" type="submit" value="Email" />
          <input name="reset" type="reset" value="Reset" />
          <input name="submitted" type="hidden" value="true" />
          </fieldset>
          </form>' ;
          }
//End PHP
?>
</body>
</html>


This block of code only display the form if the $_POST['submitted'] is NOT assigned the value of "true". If the form has NOT been submitted, the $_POST['submitted'] variable will be empty and the form will be displayed. If the $_POST['submitted'] variable DOES have the value "true", then the form will not be displayed and the error checking and mail will try to be sent.

That's it! :o

I hope you liked this tutorial and I will be writing another one soon on how to add HTML to the email and how to add attachments to the email if people on the forum would like.

Full Email Script:

The script below is the full PHP script. It has some extra added features such as counting the words of the email and a couple of other cool little things. Nothing hard at all, just cool and useful. If you have any questions or if I accidentally skipped something please let me know :)



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Create Email</title>
</head>
<body>

<?php

//Check to see if the form has been submitted
if (isset($_POST['submitted'])) {
       
       
//Create an array that will contain all of the errors if ant are to occur once the script runs
        $errors
= array() ;
       
       
//Validate all user input
       
if (!empty($_POST['to'])) {
                $to
= trim(strip_tags($_POST['to'])) ;
       
} else {
                $errors
[] = 'You must enter a <b>to</b> address.' ;
       
}
       
       
if (!empty($_POST['from'])) {
                $from
= "From: {$_POST['from']}" ;
                trim
(strip_tags($from)) ;
       
} else {
                $errors
[] = 'You must enter a <b>from</b> address.' ;
       
}
       
       
if (!empty($_POST['subject'])) {
                $subject
= trim(strip_tags($_POST['subject'])) ;
       
} else {
                $errors
[] = 'You must enter a <b>subject</b>.' ;
       
}
       
       
if (!empty($_POST['message']) && $_POST['message'] != 'Enter Your Message Here...') {
                $message
= trim(strip_tags($_POST['message'])) ;
       
} else {
                $errors
[] = 'You must enter an original <b>message</b>.' ;
       
}
       
       
//Check to make sure there were no errors while running the script
       
if (empty($errors)) {
               
               
//Everything is okay here
       
               
//Create the email and mail
               
if (mail($to , $subject , $message , $from)) {
                        echo
'<p>Your email has been sent!</p>' ;
                       
                       
//Check to see how many words there are in the email
                       
if (str_word_count($message) > 1) {
                                echo
'<p>There were ' . str_word_count($message) . ' words in your email.</p>' ;
                       
} else {
                                echo
'<p>There was ' . str_word_count($message) . ' word in your email.</p>' ;
                       
}
                       
                       
//Check to see how many characters there are in the email
                       
if (strlen($message) > 1) {
                                echo
'<p>There were ' . strlen($message) . ' characters in your email.</p>' ;
                       
} else {
                                echo
'<p>There was ' . strlen($message) . ' character in your email.</p>' ;
                       
}
                       
                        echo
'<p><a href="http://your_web_site_here.com/mail.php">Click Here to Send Another Email</a>' ;
                       
               
} else {
                        echo
'<p>There was an error sending your email, please try again.</p>' ;
               
}
               
       
} else {
               
               
//There were errors in the submission
               
//Use a foreach loop to loop through the errors array
               
//Print out Errors Heading before foreach loop
                echo
'<h2>Errors</h2>' ;
               
               
foreach ($errors as $msg) {
                        echo
"- $msg<br />" ;
               
}
               
       
}
       
} else {

//The script has not been submitted yet
//Display the HTML form
echo
'<form action="mail.php" method="post">
          <fieldset><legend>Enter your information in the form below:</legend>
          <p>To: <input name="to" type="text" size="30" /></p>
          <p>From: <input name="from" type="text" size="30" /></p>
          <p>Subject: <input name="subject" type="text" size="30" /></p>
          <p>Message:</p> <p><textarea name="message" cols="50" rows="10">Enter Your Message Here...</textarea></p>
          <input name="submit" type="submit" value="Email" />
          <input name="reset" type="reset" value="Reset" />
          <input name="submitted" type="hidden" value="true" />
          </fieldset>
          </form>'
;
         
}

//End PHP
?>

</body>
</html>
1

No comments:

Post a Comment

Do you think it could be useful for you? Share your thoughts with us!