An Easy to Use PHP Email Blast Utility

Introduction
 
Recently I was working on a website for a customer who asked me to import a mailing list to a mysql database table on the site. This was going to be run through an “email blast” utility, which also had to facilitate html so it could send through images and rich text. Although there are PHP software utilities that are already made for this, I decided to make my own for the purpose of learning more about how the process really works. I have included screen snapshots as well as programming code that illustrates some of the more specialized custom software that comprises this email blast utility.

Select recipients for the email blast from a list
 
The operator is first required to log in with a user id and password that will be authenticated with its stored counterparts in a mysql data table on the site (see image below).

log in
 
Here is the PHP code that will authenticate the user’s log in credentials after the “Login” button has been clicked:
  1. <?php    
  2.    // connect to the mysql database with predefined  
  3.    // constants from the included 'generic_config.php' file.  
  4.    $conn = mysql_connect(DB_HOSTX, DB_USERX, DB_PASSWORDX) or die('Could not connect: ' . mysql_error());  
  5.    $db_selected = mysql_select_db(DB_NAMEX, $connor die('Could not select database');     
  6.    $query_rsLogin = "SELECT * FROM generic_admin_datatable";  
  7.    $rsLogin = mysql_query($query_rsLogin$connor die(mysql_error());  
  8.    $totalRows_rsLogin = mysql_num_rows($rsLogin);  
  9.       if ( $totalRows_rsLogin >= 1 ) {  
  10.       $flagvar3 = 1;  
  11.       $rowx = mysql_fetch_row($rsLogin);  
  12.          if ( $_POST['uservar'] == $rowx[0] && $_POST['passvar'] == $rowx[1] ) {  
  13.   
  14.          // set the php session variable to 'YES' so the  
  15.          // email address listing page won't bounce us   
  16.          // back to this one.  
  17.          $_SESSION['getin'] = "YES";  
  18.          // initialize the php session variable to the  
  19.          // first row of the listed email addresses.  
  20.          $_SESSION[start_row] = 0;  
  21.          $flagvar3 = 0;  
  22.   
  23.          // set the 'blastready' field for all the email   
  24.          // addresses to 'NO'.  
  25.          mysql_query("UPDATE generic_mailing_list SET blastready = 'NO'"or die('Query failed: ' . mysql_error());  
  26.   
  27.          }  
  28.       }  
  29.    mysql_free_result($rsLogin);  
  30.    mysql_close($conn);  
  31.   
  32.       // redirect to the email address listing page.  
  33.       header("Location: http://www.genericsite.com/blast/emailblastlist.php");  
  34. ?> 

Upon successful log in, the operator will be redirected to a web page that shows a listing of email recipients (see image below). This is populated with email addresses and the first and last names from the mysql data table on the site. Notice there are 2 sets of navigation buttons at the top. The operator may move backwards and forwards through the list by 12 or 100 rows with each click.

listing of email recipients
 
If the operator wants to do a selective email blast to the listing of recipients, then the “Add To Blast” link to the right of each chosen row needs to be clicked. This will change the default status of “NO” under the “Email Blast?” column to “YES” (see image below).
 
Email Blast

Here is the PHP code that switches the “Email Blast?” column to “YES” for a selected row from the listing of recipients:
  1. <?php  
  2.   
  3. session_start();      
  4.   
  5. // this configuration file contains predefined  
  6. // constants used to connect to the server and database.  
  7. include 'generic_config.php';  
  8.   
  9.    // assign the passed email address variable into  
  10.    // a php session variable.  
  11.    $_SESSION[at] = $_GET['var'];  
  12.    
  13.       // connect to the mysql database with predefined  
  14.       // constants from the included 'generic_config.php' file.  
  15.       $conn = mysql_connect(DB_HOSTX, DB_USERX, DB_PASSWORDX) or die('Could not connect: ' . mysql_error());  
  16.       $db_selected = mysql_select_db(DB_NAMEX, $connor die('Could not select database');     
  17.   
  18.          // set the 'ready for email blast' column in the listing to 'YES' for  
  19.          // the passed email address.  
  20. mysql_query("UPDATE generic_mailing_list SET blastready = 'YES' WHERE emailaddress = '".$_SESSION[at]."'"or die('Query failed: ' . mysql_error());  
  21. mysql_close($conn);  
  22.   
  23.             // redirect to the email address listing page.  
  24.             header("Location: http://www.genericsite.com/blast/emailblastlist.php");    
  25.   
  26. ?> 

If sending an email to all recipients in the listing is desired, then nothing needs to be clicked on this web page. That will be taken care of in the next one where the email is being composed for the blast operation. To go to that web page, just click the “Email Blast” button at the top of the page.
 
Next, fill out the email web page and send out the blast!
 
This next web page is where the operator will compose the content for the email blast (see image below).

operator
 
Notice the “Who to email:” combo box control. By default it is set to “Selected” for a selective email blast operation. As mentioned previously, this designator is meant for choosing specific email recipients from the prior web page. The “All” designator will blast the email to all recipients from the list.
 
Also, the text area for the message body has been embellished with a rich text editor, “CKEDITOR”. I declared the text area for the email message, which I named “MESSAGEBOARD”. I then used the script tag enclosed directive CKEDITOR.replace(‘MESSAGEBOARD’) to integrate the rich text editor into the text area as shown below:
  1. <br><br>  
  2. <H1>EMAIL BLAST</H1>  
  3. <br><br>  
  4.   
  5. <!--inputs for subject and message.-->  
  6. <H2>    My Subject:  <input name="SUBJECT" type="text" size="40" maxlength="40" value="<?php echo $_SESSION['mysubject']; ?>"></H2>  
  7. <H2>    My Message:  <textarea name="MESSAGEBOARD" cols="50" rows="10"><?php echo $var = isset($_SESSION['post_html']) ? $_SESSION['post_html'] : ''; ?>  
  8.   
  9.     <!--embellish the message field with CKEditor to format for rich text.-->  
  10.     <script>  
  11.     CKEDITOR.replace( 'MESSAGEBOARD' );  
  12.     </script>  
  13.   
  14.         <!--dropdown list for 'Selected' or 'All' to direct php email blast routine for what type of blast.-->  
  15.         <h2>    Who to email:       
  16.             <select name="towhom" size="2">  
  17.         <option selected="">Selected</option>  
  18.         <option>All</option>  
  19.         </select>  
  20.         </h2>  
  21.   
  22. <!--click to go to email blast scroll list or email blast processing.-->  
  23. <h2>    <input name="submit_email" value="Send Email Blast" type="submit"><input name="submit_return_to" value="Return To Mail List" type="submit"></h2>  
  24.   
  25. <!--upload an image file from user's local computer and subsequently paste in the message field.-->  
  26. <h2>    <label for="file">Filename:    </label><input name="file" id="file" type="file"><input name="gogetem" value="Upload" type="submit"></h2>  

Next, the operator begins to compose the email blast message as shown below:

compose the email blast message
 
Notice the file name of an image file has been selected using the “Browse” button from the file upload feature near the bottom of the web page. You can see the name of the selected image file just to the right of the “Browse” button. If an upload image file has not been selected, then it will say “No file selected.” instead as shown in the snapshot that preceded this one. The “Upload” button has not yet been clicked, but here is the code it runs in PHP when it is:
  1. <?php  
  2. // upload an image to the website in the folder called  
  3. // 'uploads_4_emailblast'. this will be positioned in   
  4. // the message area where the text cursor is.  
  5. if ($_FILES["file"]["error"] > 0)  
  6. {  
  7. echo "Error: " . $_FILES["file"]["error"] . "<br>";  
  8. else {  
  9. echo "Upload: " . $_FILES["file"]["name"] . "<br>";  
  10. echo "Type: " . $_FILES["file"]["type"] . "<br>";  
  11. echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";  
  12. echo "Stored in: " . $_FILES["file"]["tmp_name"];  
  13.   
  14. move_uploaded_file($_FILES["file"]["tmp_name"], "/home1/generic/public_html/uploads_4_emailblast/" . $_FILES["file"]["name"]);  
  15. $_SESSION['post_html'] = $_POST['MESSAGEBOARD'] . "<br>";  
  16. $_SESSION['post_html'] .= "<p><img src='http://www.genericsite.com/uploads_4_emailblast/" . $_FILES["file"]["name"] . "'></p><br>";  
  17. }  
  18. ?> 

After the selected image file has been uploaded to the text area where the cursor is positioned, the result looks like this:

result
 
Next, the “Send Email Blast” button is clicked and the composed email in the web page is “blasted” to the chosen recipients from the listing web page. Below is the PHP code for this. Notice how I include the headers “$headers  .= "MIME-Version: 1.0\r\n";” and “$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";” to facilitate HTML in the body of the message:
  1. <?php  
  2.   
  3. session_start();  
  4.   
  5. // this configuration file contains predefined  
  6. // constants used to connect to the server and database.  
  7. include 'generic_config.php';  
  8.   
  9. // initialize data verification variables.  
  10. $flagvar = 0;  
  11. $flagvar2 = 0;  
  12. $flagvar3 = 0;  
  13.   
  14.    // processing for sending out the "email blast".  
  15.    if ($_POST['submit_email']) {  
  16.   
  17.       // test to see if the subject and message fields are empty.  
  18.       if ( emptyempty($_POST['SUBJECT']) ) {  
  19.       $flagvar2 = 1;  
  20.       $flagvar = 1;  
  21.       }  
  22.       if ( emptyempty($_POST['MESSAGEBOARD']) ) {  
  23.       $flagvar3 = 1;  
  24.       $flagvar = 1;  
  25.       }  
  26.   
  27.     // if subject and message fields were typed into,  
  28.     // then proceed with "email blast".  
  29.     if ( $flagvar == 0 ) {  
  30.   
  31.     // remove slashes from the message.  
  32.     $body = $_POST['MESSAGEBOARD'];  
  33.     $body = stripslashes($body)."<br><p>Email Sender: anyone@wherever.com</p>";  
  34.   
  35.     // set headers for 'From' field and also set up  
  36.     // to format html.  
  37.     $headers = "From: anyone@wherever.com\r\n";  
  38.     $headers  .= "MIME-Version: 1.0\r\n";  
  39.     $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";  
  40.   
  41.     // connect to the mysql database with predefined  
  42.     // constants from the included 'generic_config.php' file.  
  43. $conn = mysql_connect(DB_HOSTX, DB_USERX, DB_PASSWORDX) or die('Could not connect: ' . mysql_error());  
  44.     $db_selected = mysql_select_db(DB_NAMEX, $connor die('Could not select database');     
  45.   
  46.         // if the dropdown box was clicked for 'Selected', then  
  47.         // perform the "email blast" for records in the mail list  
  48.         // table where the 'blastready' field is equal to 'YES'.  
  49.         // otherwise, "email blast" for everyone.  
  50.         if ( $_POST['towhom'] == "Selected" ) {  
  51. $query_rsLogin = "SELECT * FROM generic_mailing_list WHERE blastready = 'YES'";  
  52.         } else {  
  53.         $query_rsLogin = "SELECT * FROM generic_mailing_list";  
  54.         }  
  55.   
  56. // create queried resource '$rsLogin' and get  
  57. // the total number of rows.  
  58. $rsLogin = mysql_query($query_rsLogin$connor die(mysql_error());  
  59. $totalRows_rsLogin = mysql_num_rows($rsLogin);  
  60.   
  61.    // send out "email blast" if the total rows in the previously  
  62.    // queried result is greater than or equal to 1.  
  63.    if ( $totalRows_rsLogin >= 1 ) {  
  64.       while ($rowx = mysql_fetch_row($rsLogin)) {  
  65.       // get the email address from the queried result.  
  66.       $emailx = $rowx[2];  
  67.       // send the email, then loop around for next row  
  68.       // in the queried result.  
  69.       mail($emailx$_POST['SUBJECT'], $body$headers);  
  70.       }  
  71.    }  
  72.     // free the queried data resource.  
  73.     mysql_free_result($rsLogin);  
  74.     // close the server connection.  
  75.     mysql_close($conn);   
  76.     }   
  77.    }    
  78. ?> 

Conclusion
 
This is an easy to use utility that makes short work of sending out an email blast. It’s perfect for email marketing, invitations, greetings, etc. This PHP code can be easily modified to accommodate a wide range of email blast objectives.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now