Richland College Multimedia Learning Center

Digital Media Programming with PHP and MySQL

Digital Media Programming with PHP and MySQL

PHP E-mail

The mail( ) Function

The PHP mail( ) function can be used as a mail processor for a form, or as a mailing-list manager. It uses an SMTP server to actually send the e-mail messages.

Here is a list of the parameters that the mail( ) function accepts:

Note that $to, $subject, and $message are required parameters.

The $additional_headers parameter is technically optional, but you actually are required to use it since this is the parameter where you put the sender ("from") information. The SMTP server will not send e-mail without a "from" address.

If you are using Freehostia as your Web hosting service, here are some preliminary notes on what you will need to do, in order to get your mail() submission to work:


An E-mail Form

We will be looking at these e-mail pages during this class.

The first file is sendEmailForm.php:

<?php require("securityStuff.php"); ?>
<!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" xml:lang="en" lang="en">

<head>
  <title>Send an E-mail</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <link rel="stylesheet" type="text/css" href="PHPstyles.css" />
</head>

<body>
  <h3>Send an E-mail</h3>
  <form name="form1" method="post" action="sendEmailAction.php">
    <table>
      <tr>
        <td>Destination E-mail Address (To): </td>
        <td><input type="text" name="email_destination" size="60"
              <?php if (isset($_SESSION["email_destination"])){?>
                value="<?php echo $_SESSION["email_destination"] ?>"
              <?php } ?> />
        </td>
      </tr>
      <tr>
        <td>E-mail Subject: </td>
        <td><input type="text" name="email_subject" size="60"
              <?php if (isset($_SESSION["email_subject"])){?>
                value="<?php echo $_SESSION["email_subject"] ?>"
              <?php } ?> />
        </td>
      </tr>
      <tr>
        <td>E-mail Message: </td>
        <td><textarea name="email_body" cols="40" rows="4"><?php if (isset($_SESSION["email_body"])){
                echo stripslashes($_SESSION["email_body"]);} ?></textarea>
        </td>
      </tr>

      <tr>
          <td valign="top"> </td>
          <td>
            <img src="<?php echo $securityImage?>" width="200" height="30" alt="" />
          </td>
      </tr>

      <tr>
          <td class="colOne">Type the letters that you see in the image
              above, into this field (The letters are case sensitive):</td>
          <td valign="bottom"><input type="text" name="securityPhrase" id="securityPhrase" /> (For security)</td>
      </tr>

      <tr>
        <td colspan="2"><input type="submit" value="Send Your E-mail" /></td>
      </tr>
    </table>
  </form>
</body>
</html>

The Action Page

The form's action page is sendEmailAction.php:

<?php
  session_start();
  error_reporting(E_ALL);
  if (isset($_POST["email_destination"])) $_SESSION["email_destination"] = $_POST["email_destination"];
  if (isset($_POST["email_subject"])) $_SESSION["email_subject"] = $_POST["email_subject"];
  if (isset($_POST["email_body"])) $_SESSION["email_body"] = stripslashes($_POST["email_body"]);
  if (isset($_POST["securityPhrase"]) && isset($_SESSION["securityPhrase"]))
  {
    $checkSecurity = true;
    if (strcmp($_POST["securityPhrase"],$_SESSION["securityPhrase"]) != 0)
    {
      $sendEmail = false;
    }
    else
    {
      $sendEmail = true;
    }
  }
  else
  {
    $checkSecurity = false;
  }
?>
<!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" xml:lang="en" lang="en">

<head>
  <title>Send an E-mail</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
</head>

<body>
<?php
  if ($checkSecurity == true)
  {
    if ($sendEmail == false)
    {
      echo "<h3>You need to go back and re-type the security phrase.</h3>";
      echo "<h4>(The characters are case sensitive.)</h4>";
    }
    else
    {
    	try
    	{
	      // Specify the Mail Server:
	      ini_set("SMTP","mbox.freehostia.com");

	      // Specify an SMTP Port Number 425 for Freehostia
	      ini_set("smtp_port","425");

	      // Specify the return address to use:
	      $from    = "jlink@tigersarecute.xyz";
	      ini_set("sendmail_from", "$from");
	      ini_set("sendmail_password", "classPwd1");
	      $to      = $_POST["email_destination"];
	      $subject = $_POST["email_subject"];
	      $message = stripslashes($_POST["email_body"]);
	      // In case any of our lines are larger than 70 characters, we should use wordwrap()
	      $message = wordwrap($message, 70);
	      // To send HTML mail, the Content-type header must be set
	      $headers  = 'MIME-Version: 1.0' . "\r\n";
	      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	      $headers .= 'From: ' . $from . "\r\n";

	      if ($message != "" && $from != "" && $to != "" && $subject != "")
	      {
	        if ( !preg_match( "/[\r\n]/", $from ) && !preg_match( "/[\r\n]/", $to ))
	        {
	           if (mail($to, $subject, $message, $headers))
	            {
	              echo "<h3>The mail was successfully submitted to the mail server.</h3>";
	              echo "<br /><br />";
	              echo "<a href='sendEmailForm.php'>Send Another E-mail Message</a>";
	            }
	            else
	            {
	              //echo "<h3>There was a problem trying to submit the mail to the mail server.</h3>";
	              throw new Exception('<h3>There was a problem trying to submit the mail to the mail server.</h3>');
        	    }
	      	}
	      }
	      else
	      {
	        echo "<h3>You need to go back to the form and enter this required information:</h3>";
	        if ($to == "")
	        {
	          echo "<br />    To: address";
	        }
	        if ($subject == "")
	        {
	          echo "<br />    Subject";
	        }
	        if ($message == "")
	        {
	          echo "<br />    E-mail Message";
	        }
	      }
	}
    	catch(Exception $e)
    	{
    	    echo $e->getMessage();
    	}
    }
  }
  else
  {
    echo "<h3>The system has experienced a temporary problem.</h3>";
    echo "<br /><a href='sendEmailForm.php'>Please try again</a>";
  }
?>
</body>
</html>

The Security Include File

The include file is securityStuff.php:

<?php
  session_start();

  $secIndex = rand(1,6);

  $secPhraseArray = array();
  $secPhraseArray[1] = "ABCD";
  $secPhraseArray[2] = "EFGH";
  $secPhraseArray[3] = "IJKL";
  $secPhraseArray[4] = "MNOP";
  $secPhraseArray[5] = "QRST";
  $secPhraseArray[6] = "UVWX";

  $securityImage = "images/securityImage$secIndex.jpg";

  $_SESSION["securityPhrase"] = $secPhraseArray[$secIndex];
?>

You can see the above code running here.

Please note these points about the above code:


E-mailing an Attachment

The following pages will show you how to attach a file to an e-mail, for sending.

You can see the sample pages running here.

The first page in this sample code is sendEmailAttachmentForm.php:

<?php require("securityStuff.php"); ?>
<!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" xml:lang="en" lang="en">
<head>
  <title>Send an Email with an Attachment</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <link rel="stylesheet" type="text/css" href="PHPstyles.css" />
</head>

<body>
  <h3>Send an E-mail</h3>
  <form name="form1" method="post" action="sendEmailAttachmentAction.php"
        enctype="multipart/form-data">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <table>
      <tr>
        <td>Destination E-mail Address (To): </td>
        <td><input type="text" name="email_destination" size="60"
              <?php if (isset($_SESSION["email_destination"])){?>
                value="<?php echo $_SESSION["email_destination"] ?>"
              <?php } ?> />
        </td>
      </tr>
      <tr>
        <td>E-mail Subject: </td>
        <td><input type="text" name="email_subject" size="60"
              <?php if (isset($_SESSION["email_subject"])){?>
                value="<?php echo $_SESSION["email_subject"] ?>"
              <?php } ?> />
        </td>
      </tr>
      <tr>
        <td>E-mail Message: </td>
        <td><textarea name="email_body" cols="40" rows="4"><?php if (isset($_SESSION["email_body"])){
                echo stripslashes($_SESSION["email_body"]);} ?></textarea>
        </td>
      </tr>
      <tr>
        <td>Attach a File: (optional)</td>
        <!-- Name of file input element determines name in $_FILES array -->
        <td><input type="file" name="email_attachment" size="60" /></td>
      </tr>

      <tr>
          <td valign="top"> </td>
          <td>
            <img src="<?php echo $securityImage?>" width="200" height="30" alt="" />
          </td>
      </tr>

      <tr>
          <td class="colOne">Type the letters that you see in the image
              above, into this field (The letters are case sensitive):</td>
          <td valign="bottom"><input type="text" name="securityPhrase" id="securityPhrase" /> (For security)</td>
      </tr>

      <tr>
        <td colspan="2"><input type="submit" value="Send Your E-mail" /></td>
      </tr>
    </table>
  </form>
</body>
</html>

The action page is sendEmailAttachmentAction.php:

<?php
session_start();
require_once "Mail.php";
require_once("Mail\mime.php");
if (isset($_POST["email_destination"])) $_SESSION["email_destination"] = $_POST["email_destination"];
if (isset($_POST["email_subject"])) $_SESSION["email_subject"] = $_POST["email_subject"];
if (isset($_POST["email_body"])) $_SESSION["email_body"] = stripslashes($_POST["email_body"]);
if (isset($_POST["securityPhrase"]) && isset($_SESSION["securityPhrase"]))
{
  $checkSecurity = true;
  if (strcmp($_POST["securityPhrase"],$_SESSION["securityPhrase"]) != 0)
  {
    $sendEmail = false;
  }
  else
  {
    $sendEmail = true;
  }
}
else
{
  $checkSecurity = false;
}
?>
<!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" xml:lang="en" lang="en">
<head>
  <title>Send an Email</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <link rel="stylesheet" type="text/css" href="PHPstyles.css" />
</head>

  <body>
    <?php
    if ($checkSecurity == true)
    {
      if ($sendEmail == false)
      {
        echo "<h3>You need to go back and re-type the security phrase.</h3>";
        echo "<h4>(The characters are case sensitive.)</h4>";
      }
      else
      {
        if (isset($_FILES['email_attachment']['name']) && $_FILES['email_attachment']['name'] != "")
        {
          $sendFileAttachmentTried = TRUE;

          $target_path = "tmp/";
          $baseFileName = basename( $_FILES['email_attachment']['name']);
          $target_path = $target_path . $baseFileName;
          if(move_uploaded_file($_FILES['email_attachment']['tmp_name'], $target_path))
          {
            $fileUploaded = TRUE;
            $fileatt = $target_path;
            $pathInfo = pathinfo($target_path);
            $fileattname = $baseFileName;
          }
          else
          {
            echo "<p>There was an error uploading file " .
            $baseFileName . "</p>";
            switch ($_FILES['email_attachment']['error'])
            {
              case 2: $errorDescr = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
              break;

              case 3: $errorDescr = "The uploaded file was only partially uploaded.";
              break;

              case 4: $errorDescr = "No file was uploaded.";
              break;

              case 6: $errorDescr = "Missing a temporary folder.";
              break;

              case 7: $errorDescr = "Failed to write file to disk.";
              break;

              case 8: $errorDescr = "File upload stopped by extension.";
              break;

              default: $errorDescr = "There was an unknown error code.  The code was " . strval($_FILES['email_attachment']['error']) . ".";
            }
            echo "<p>$errorDescr</p>";
            $fileUploaded = FALSE;
          }
        }
        else
        {
          $sendFileAttachmentTried = FALSE;
          $fileUploaded = FALSE;
        }
        // Specify the Mail Server:
        ini_set("SMTP","mbox.freehostia.com");

        // Specify an SMTP Number 25 and 8889 are valid SMTP Ports.  Freehostia might use 465.
        ini_set("smtp_port","25");

        // Specify the return address to use:
        $from    = "jlink@tigersarecute.xyz";
        ini_set("sendmail_from", "$from");
        $to      = $_POST["email_destination"];
        $subject = $_POST["email_subject"];

        $messagestuff = stripslashes($_POST["email_body"]);
        // In case any of our lines are larger than 70 characters, we should use wordwrap()
        $messagestuff = wordwrap($messagestuff, 70);
        $messagestuff = "
        <html>
        <head>
        <title>An HTML E-mail Message</title>
        <style type='text/css'>body{font-family: Arial, sans-serif;}</style>
        </head>
        <body>
        <p>" . $messagestuff .
        "</p>
        </body>
        </html>";
        if ($to != "" && $subject != "" && $_POST["email_body"] != "" && $from != "")
        {
          if ($fileUploaded)
          {
            $message = new Mail_mime();
            $message->setHTMLBody($messagestuff);
            $message->addAttachment($target_path);
            $body = $message->get();
            $extraheaders = array("From"=>$from, "Subject"=>$subject, "Reply-To"=>$from);
            $headers = $message->headers($extraheaders);
            $mail = Mail::factory("mail");
            if ( !preg_match( "/[\r\n]/", $from ) && !preg_match( "/[\r\n]/", $to ) && $mail->send($to, $headers, $body))
            {
              echo "<h3>The mail was successfully submitted to the mail server. (A)</h3>";
              echo "<br /><br />";
              echo "<a href='sendEmailAttachmentForm.php'>Send Another E-mail Message</a>";
            }
            else
            {
              echo "There was a problem trying to submit the mail to the mail server. (A)";
            }
          }
          else
          {
            if (!$sendFileAttachmentTried)
            {
              //set some header values for HTML e-mail:
              $headers = 'From: ' . $from . "\r\n";
              $headers .= 'Reply-To: ' . $from . "\r\n";
              $headers .= 'MIME-Version: 1.0' . "\r\n";
              $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
              if (!preg_match( "/[\r\n]/", $from ) && !preg_match( "/[\r\n]/", $to ) && mail($to, $subject, $messagestuff, $headers))
              {
                echo "<h3>The mail was successfully submitted to the mail server. (B)</h3>";
                echo "<br /><br />";
                echo "<a href='sendEmailAttachmentForm.php'>Send Another E-mail Message</a>";
              }
              else
              {
                echo "There was a problem trying to submit the mail to the mail server. (B)";
              }
            }
            else
            {
              echo "There was a problem uploading your file attachment. Please try again. (B)";
            }
          }
        }
        else
        {
          $missingStuff = "<h3>You need to go back to the form and enter this required information:</h3>\n";
          if ($from == "")
          {
            $missingStuff .= "<p>From: address</p>\n";
          }
          if ($to == "")
          {
            $missingStuff .= "<p>To: address</p>\n";
          }
          if ($subject == "")
          {
            $missingStuff .= "<p>Subject:</p>\n";
          }
          if ($_POST["email_body"] == "")
          {
            $missingStuff .= "<p>E-mail Message:</p>\n";
          }
          echo $missingStuff;
        }
      }
    }
    else
    {
      echo "<h3>The system has experienced a temporary problem.</h3>";
      echo "<br /><a href='sendEmailAttachmentForm.php'>Please try again</a>";
    }
    ?>
  </body>
</html>

Please note these points about the above code: