Sending Emails with PHP

Emailing from a server is a fairly common task. We can email for any number of reasons including:

This last reason is the one most commonly used. While we can always use a "mailto:" in a link to allow a user to email us, this does not always work. If the user doesn't have an email client on their machine, they will not be able to use this link. (GMail, Yahoo, and other web based mail clients cannot recognize these links normally.) Also, spammers can pull these email addresses and spam you (more). By using an email form, both of these scenarios are handled adequately.

Example #1

The following example assumes that you have a anonymous feedback form with a text area called comment, and the submit button named submit, using a POST form method.

We will put this in a file called feedback-thank-you.php, and it will come from a file called feedback.php.

if(isset($_POST['submit'])) {
     mail('[email protected]', 'anonymous feedback', $_POST['comment']);
}
....
<HTML document thanking the person for contacting them>

The PHP Code Explained

The first line has three new parts to deal with:

$_POST - When a user submits information via a form, it uses a method of either GET or POST. For PHP to read this information, it creates what is technically called an associative array. These arrays are called $_GET (for the GET method) or $_POST (for the POST method). Being an associative array means you can access the form field by putting the form elements name inside the square brackets, surrounded by single or double quotes.

if(<condition>) {} - Previously, all of our commands ran sequentially regardless of inputs from the user, or circumstances on the server. The if command allows us to choose to execute a set of commands based upon some condition. A condition is essentially a question which can be answered in a yes/no or true/false manner. If the condition is true, then the commands inside the braces are run. If the condition is not true, then PHP will skip to the end of the closing brace and continue on from there.

isset(<variable>) - isset() gives PHP a true or false statement depending upon if there is information in what is passed to isset() via a parameter. A parameter is information passed to a function, that it needs to run properly. If we don't pass this information, then the function cannot run. In this case if the user posted an element called submit with the form, then this command will give us true response.

mail(<to>, <subject>, <mail body>) - The mail function allows us to send the mail. It has three required parameters, and an optional parameter. We have hard coded who the email is going to get sent to ('[email protected]'), and the subject line ('anonymous feedback'). The body of the email comes from the textarea (or what ever the form field was) that was named comment (because of the $_POST['comment']).

Example #2

In this example we will put this in a file called email-thank-you.php, and it will come from a file called contact-us.php. We want to be able to collect several fields in this example, including the user's name, their email address, and the comment itself. Assuming a form with the fields submit, name, email, and comment are all used, our code could look like the following:

if(isset($_POST['submit'])) {
  $body = $_POST['name'] ."/n";
	$body .= $_POST['email'] ."/n";
	$body .= $_POST['comment'];
  mail('[email protected]', 'Comment Form Filled Out', $body);
} else {
	header('Location: contact-us.php');
	exit(0);
}
<HTML document thanking the person for contacting them>

The PHP Code

Let's look at what is new.

$body - This is a variable. The name you give it doesn't matter. It just needs to be consistently used. You could have named it $Bob, $joe, or $ZZ, and PHP would understand it. However, good programming practice says to make the name meaningful. Variables are used to store information for later use in our program. In this case, we are going to build the body of our email, hence the name.

Did you notice the dollar sign ($)?

In PHP variables start with a dollar sign. This is how we can quickly know we are working with a variable, and not a function.

We built the contents of the variable by assigning it a value. The equal sign (=) assigns the value on the right side of the equal to the variable on the left side. Therefore we can only have one variable on the left side of our equal sign. In this case we are assigning the value which the user entered into the name form element, to our $body variable. The ."/n" is a special string we are going to append to what the user entered. The "." is the command PHP uses to append (or combine one after another) multiple strings together. The /n is a special string. The two characters combined as such, generates what is known as a new line. It is equivalent to hitting the enter key on the keyboard, but since our program can't do that, we use the new line characters. By adding a new line to the end of each value that the user submitted, it makes it easier to read in the email, the last value we add to our string, we don't need the new line because nothing is going after it.

Why isn't the value overwritten in the other lines? Look closely, and you'll see that they have a ".=", not just the "=". This means that we are going to append a value to the the existing value. This only works with strings. If our variable stored a number, we would use different commands.

else { } - Earlier we talked about the if statement. With the if statement, we get to perform some commands if the condition is true. However, what if we wanted to do something if the condition was false, or a no answer? This is what the else block is for. Everything within the braces gets done if the if condition was false. In this case, if we somehow got to the page without using the form, it will run this block of code.

header('Location: contact-us.php'); - Headers are sent to the browser to let them know about the information being sent between the client and the server. As users, we never see these headers, however they are always there. As developers we can sometimes use these headers to perform various tasks without the user's control. In this case, specifying a Location will tell the browser to automatically load a new page, in this case the page with the contact form.

exit(0); - This just ensures that no other commands are run on this page, ensuring that it will redirect the user to the correct page.