[wpdm_file id=3]
This quick tutorial will show how to send an email using PHP. There is a video demo below if you want to view that as well.
Emailing from a server is a fairly common task. We can email for any number of reasons including:
- Letting an administrator know when something doesn’t work.
- Giving a user access to a document they had to give information to get.
- Resetting a user’s password.
- Providing information from a user to the web site owner. (This 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. Here are common problems with using a mailto in a link:
- If the user doesn’t have an email client on their machine, they will not be able to use this link. (This is especially true in public access computers like at libraries and school labs.)
- GMail, Yahoo, and other web based mail clients cannot recognize these links normally.
- Spammers can pull these email addresses and spam you. By using an email form, both scenarios are handled adequately.
For this example, we will build a Contact Us form. It will be made up of three (3) sections, a contact form, a form processor – to send the email, and a thank you page.
Contact Form
The HTML Code Explained
The UL and LI tags are to layout the form, and the look is controlled with CSS.
This is just the form area. The form is set to send information to the server. The file that will receive the information is in the action attribute, and how the information will be sent is through the method attribute.
This form is assuming that a webpage, with styles, scripts, and header/footer/sidebar information exists and surrounds this form.
The Contact Us Thank You Page
This will be a basic HTML file that just thanks the user for sending the information. It lets the user know that the form was submitted.
The Contact Us Send Page
Step 1 – Checking the Submission
The first step is to check to see if the user actually submitted something through the form. Using the isset() method helps with that.
if(isset($_POST['Submit'])) { // do code } else { // do other code block header('Location: contact-us.html'); }
The PHP Code Explained
Notes on Sending Mail
Not all web servers/hosts will allow you to send email from the server, or they limit the number of emails you can send. This is to cut down on spam. If you do not have any errors, but cannot send email, check with your host provider to see if they are blocking mail being sent.
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.
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.html’); – 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.
Obviously you will want to change the file name to match what your file will be.
Step 2 – Building our Email Message
// submitted to server through form // build the email message by using // info received by the HTML form $msg = 'Name: ' .$_POST['name'] ."\n" 'Email: ' .$_POST['email'] ."\n" 'Comment: ' ."\n" .$_POST['comment']; // send email using PHP's built in // command, mail() mail('example@example.com', 'Sample Comments', $msg); // redirect to the thank you page header('location: contact-us-thank-you.html'); // exit this script - just to make sure nothing else gets run exit(0);
The PHP Code Explained
$msg – 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 message body of our email, hence the name. $msg, is short for message – programmers like to be “efficient” with their names.
We build the value by concatenating information from the form with labels we give it.
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 (‘example@example.com’), and the subject line (‘Sample Comments’). 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’]).
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.
Explaining the .”/n”
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.
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.
Sending Email with PHP was originally found on Access 2 Learn