To send email with PHP use the mail function. This has the following syntax:

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

The $to variable is the recipient of the email. The $subject variable is the subject of the email. The $body is the body text of the email. This can include HTML for HTML formatted emails.

All emails are made up of headers and the body. The header contains information such as who the email was from. Use the fourth $header parameter to add email headers. These include From, Cc, Bcc and non-standard ones such as X-Mailer. Your mail must include a ‘from’ value. In all variables you can use \n for a new line and \r for a carriage return

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@mysite.com' . "\r\n" .
   'Reply-To: webmaster@mysite.com' . "\r\n" .
   'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>

The above example uses a standard email header with ‘From’ and ‘Reply-To’ values as well as ‘X-Mailer’ that indicates that the email was PHP generated.

The message in the above is not very exciting. See Appendix E for a message formatted in HTML with CSS.
Note: That normal PHP rules apply. Therefore is your email message contains speech marks (which a HTML formatted one will) then these need to be escaped.

Using MySQL Data

To use an email address stored in MySQL the email address (and other details like name etc) need only be returned for the database via a SQL SELECT statement.

When building an application of this type rather than just send the messages it is a good idea to manually check the email addresses to receive your messages.

$email_sql = "SELECT customer_id, customer_email, customer_firstname, customer_surname FROM customers;";
$email_query = mysqli_query($connection, $email_sql);

For example the above could be used to generate a HTML form list of customers each with a checkbox to select the customers to email. For example:

<?php
while($row_email_list = mysqli_fetch_array($email_query)){?>
<p> 
<input name="<?php echo $row_email_list['customer_id']?>" type="checkbox" value="<?php echo $row_email_list['customer_id']?>" />
<?php echo $row_email_list['customer_firstname'];?> <?php echo $row_email_list['customer_surname'];?> || 
<?php echo $row_email_list['customer_email'];?>
</p>
<?php }?>

When checked the value of the ‘customer_id’ is submitted.

In the file that sends the mail we can loop round the $_POST super global using a foreach.

foreach($_POST as $customer_id){

Remember a foreach() will loop around the contents of an array. Our HTML form when set to method ‘post’ will post its variables as an array, the $_POST super global.

Inside the foreach loop a SQL SELECT statement can then be used to get the unique values for each email recipient and a personalized email message created.

<?php
require_once "includes/connection.inc.php";//load connection info
foreach($_POST as $customer_id){
//get the mails
$stmt = mysqli_prepare($connection, "SELECT customer_id, customer_email, customer_firstname, customer_surname FROM customers WHERE customer_id like ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $customer_id);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $customer_id, $customer_email, $customer_firstname, $customer_surname);
/* execute query */
mysqli_stmt_execute($stmt);
/* fetch SINGLE ROW data */
mysqli_stmt_fetch($stmt);
/* close Statement */
mysqli_stmt_close($stmt);
$headers = "From: somebody@mysite.com\r\n" .
       'X-Mailer: PHP/' . phpversion();
$message = "
Dear {$customer_firstname} {$customer_surname}\r\n
Thank you for choosing Firebrand Films.
";
if (mail($customer_email, 'Email Title', $message, $headers)) {
  echo("<p>Message successfully sent to {$customer_email}</p>");
 } else {
  echo("<p>Message delivery failed...</p>");
 }
}
?>

The final if/else statement is based on the whether the mail is successful. If the mail is send then a successful message is sent, and if not, a delivery failure message is output.

HTML Email

In the above example the mail message could easily have been formatted as HTML. To do so add HTML to the $message variable. You should also amend the $header variable to indicate the content is in HTML format, for example:

$path = "http://www.myserver.com/" .
$headers = "From: someone@mysite.com\r\n" .
       'X-Mailer: PHP/' . phpversion() . "\r\n" .
       "MIME-Version: 1.0\r\n" .
       "Content-Type: text/html; charset=utf-8\r\n" .
       "Content-Transfer-Encoding: 8bit\r\n\r\n";
$message = "
<!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=iso-8859-1\" />
<title>Firebrand Films - Special Offers</title>
</head><body>
<table width=\"550\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
  <tr>
    <td colspan=\"2\"><img src=\"{$path}/shopimages/logo2.gif\" alt=\"Firebrand Films\" width=\"500\" height=\"125\" /></td>
  </tr>
  <tr>
    <td><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
      <tr>
        <td><a href=\"{$path}/dvd.php\">DVD</a></td>
      </tr>
      <tr>
        <td><a href=\"{$path}/tshirts.php\">T-Shirts</a></td>
      </tr>
      <tr>
        <td><a href=\"{$path}/join.php\">Join Us Today </a></td>
      </tr>
      <tr>
        <td><a href=\"{$path}/members.php\">Members Login </a></td>
      </tr>
    </table></td>
    <td width=\"424\" align=\"left\" valign=\"top\"><h1>Special Offers</h1>
    <p>All Star Wars DVDs and T-shirts discounted. </p></td>
  </tr>
</table></body></html>
";

Note: In the above example we have used a variable $path. All the links and images in the email must have absolute URLs to function correctly. The $path variable in the above is set to the domain name of the web site referenced by the email.

Adding Unsubscribe Functionality

When sending out email newsletters and the like it is common practice to offer an ‘unsubscribe’ feature. This can be managed by having a ‘mailing_list’ type field in your MySQL database and setting it to ‘false’ for unsubscribed members.

In the email the ‘unsubscribe’ is normally a link in the email message that will pass an unique querystring value to an unsubscribe page. For example the link could use the customer_id in a querystring as follows:

<a href="http://www.myserver.com/unsubscribe.php?customer_id=123">Unsubscribe Me</a>

The unsubscribe page would then contain a SQL UPDATE statement to set the ‘mailing_list’ field to ‘false’ and a header/redirect to a confirmation page, for example:

<?php
require_once('includes/connection.inc.php'); 
$stmt = mysqli_prepare($connection, "UPDATE customers SET customer_mailing_list = 0 WHERE customer_id = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $_GET["customer_id"]);
/* execute query */
mysqli_stmt_execute($stmt);
/* close Statement */
mysqli_stmt_close($stmt);
header("Location: confirm.php"); // redirect browser
exit; // make sure no other code executed 
?>

Data Protection and Unsolicited Mail

Please do not use you new found power to send out unsolicited mail (SPAM). By maintaining personal data such as email addresses you are subject to the Data Protection Act and should always indicate if you intend to use collected email addresses for sending out newsletters etc. You should also always allow users to ‘opt out’ (as described above with the ‘unsubscribe’ feature).

Leave a Comment