Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Sending Email

One of my absolute favorite things about PHP is how easy it is to send an email. On a properly configured server, the process is as simple as using the mail() function.

mail ($to, $subject, $body);

The $to value should be an email address or a series of addresses, separated by commas. The $subject value will create the email's subject line, and $body is where you put the contents of the email. Use the newline character (\n) within double quotation marks when creating your body to make the text go over multiple lines.

The mail() function takes a fourth, optional parameter for additional headers. This is where you could set the From, Reply-To, Cc, Bcc, and similar settings. For example,

mail ('phpmysql2@dmcinsights.com',  'Question regarding Script 3.13',  $body, 'From: person@address.com');

To use multiple headers of different types in your email, separate each with \r\n:

$headers = "From: John@Doe.com\r\n";
$headers .= "Cc: Jane@Doe.com, Joe@Doe. com\r\n";
mail ('phpmysql2@dmcinsights.com',  'Question regarding Script 3.13',  $body, $headers);

As the last example in this chapter, a simple registration form will be created that will also send an email upon successful registration. While I'm at it, this example will also demonstrate an easy way to handle and report multiple form-submission errors.

To send email

  1. Begin a new PHP script in your text editor ( Script 3.13 ).
    <?php # Script 3.13 - register.php
    $page_title = 'Register';
    include ('./includes/header.html');
    
    03fig35.gif

    Script 3.13 PHP's mail() function is surprisingly easy to use.

  2. Create the conditional for checking if the form has been submitted and then create a variable to track registration errors.
    if (isset($_POST['submitted'])) {
      $errors = array();
    

    The $errors variable will store all of the accumulated errors from validating the form data. It's initialized here as an array, which is not technically required but is good programming style.

  3. Validate the name and email address.
    if (empty($_POST['name'])) {
      $errors[] = 'You forgot to enter your name.';
    }
    if (empty($_POST['email'])) {
      $errors[] = 'You forgot to enter your email address.';
    }
    

    These two text inputs are validated using the most minimal technique: making sure they aren't empty. If either is empty, a specific message is added as an element to the $errors array. In Chapter 10, "Web Application Security," you'll see how to use regular expressions to help validate a submitted email address

    .
  4. Validate the password.
    if (!empty($_POST['password1'])) {
      if ($_POST['password1'] != $_POST ['password2']) {
        $errors[] = 'Your password did not match the confirmed password.';
      }
    } else {
      $errors[] = 'You forgot to enter your password.';
    }
    

    There are two different validations for the password. First you must check that it's not empty. Second, the password must match the confirmed password. If either condition is false, another error message is added to the array.

  5. Create a conditional that checks if errors occurred.
    if (empty($errors)) {
    

    If no errors occurred, then the $errors array is still empty, and the email can be sent.

  6. Send the email.
    $body = "Thank you for registering with our site!\nYour password is '{$_POST['password1']}'. \n\nSincerely,\nUs";
    mail ($_POST['email'], 'Thank you for registering!', $body, 'From: admin@site.com');
    

    To send the email, I first build up my email body and assign that to the $body variable, and then I use the mail() function.

  7. Print a message to the user.
    echo '<h1 id="mainhead">Thank you!</h1>
    <p>You are now registered. An email has been sent to your email address confirming the information.</p><p><br /></p>';
    

    Obviously the script doesn't yet register the user, but that functionality will be added in due time.

  8. Complete the inner conditional, reporting on the errors.
    } else {
      echo '<h1 id="mainhead">Error!</h1>
      <p class="error">The following error(s) occurred:<br />';
      foreach ($errors as $msg) {
      echo " - $msg<br />\n";
      }
      echo '</p><p>Please go back and try again.</p><p><br /></p>';
    }
    

    Since $errors is an array, all of the error messages can easily be printed out using a foreach loop. The result will be a simply formatted list of problems ( Figure 3.21 ).

    03fig36.gif

    Figure 3.21 If the form isn't filled out completely, error messages are generated.

  9. Complete the main if and close the PHP tags.
    }else {
    ?>
    

    This closes the if block that checks if the form has been submitted. Now the form itself will be created, outside of the PHP tags.

  10. Create the HTML form.
    <h2>Register</h2>
    <form action="register.php" method="post">
      <p>Name: <input type="text" name="name" size="20" maxlength="40" /></p>
      <p>Email Address: <input type="text" name="email" size="20" maxlength="40" /> </p>
      <p>Password: <input type="password" name="password1" size="10" maxlength="20" /></p>
      <p>Confirm Password: <input type="password" name="password2" size="10" maxlength="20" /></p>
      <p><input type="submit" name="submit" value="Register" /></p>
      <input type="hidden" name="submitted" value="TRUE" />
    </form>
    

    There's nothing particularly new here, except that the password is requested twice. This is a smart step to take, since the password is an unreadable input ( Figure 3.22 ). If you only take the password once and the user mistypes their entry, they may not know what their password actually is.

    03fig37.gif

    Figure 3.22 The registration form…

  11. Complete the PHP page.
    <?php
    }
    include ('./includes/footer.html');
    ?>
    

    The closing curly brace completes the main conditional (that checks if the form has been submitted and displays it otherwise).

  12. Save the file as register.php, upload to your Web server, and test in your Web browser ( Figure 3.23 ).
    03fig38.gif

    Figure 3.23 …and its successful completion.

    See the sidebar "PHP mail() Dependencies" if you see an odd error message (about From headers missing or no SMTP server) or if you never receive the email.

  13. Check your email to confirm that you received the message ( Figure 3.24 ).
    03fig39.gif

    Figure 3.24 The email I received from the registration page.

  • + Share This
  • 🔖 Save To Your Account