Jump to content

Mass email script


Recommended Posts

Can anybody here look over my new script to verify that it is correct? Maybe even test it?

 

For the following code, you should replace the notification email with your own (See the bottom of the script) and replace my code block for getting the newsletter template with your own code or HTML.

 

PHP Code should be saved to file 'emailer.cron.php'

<?php
/*
* First thing we need to do is to see if there are any
* emails to be sent. We do this by looking for the 
* line '___START___' in the database and making sure
* there is no '___STOP___' after it.
*/

/*
* We first need to open a connection with the MySQL
* server, than select a database.
*/

$connection = mysql_connect("localhost","safetyha_su","HuhAspuc4e") or die("emailer.cron.php was unable to connect to the MySQL Database on line 14 (".mysql_error().")");
$selectdb   = mysql_select_db("safetyha_webadmin",$connection) or die("emailer.cron.php was unable to select the MySQL Database on line 15 (".mysql_error().")");

/*
* We have now connected to the MySQL database, lets
* search for the '___START___' command, and select
* the last match if any
*/

$query1   = "SELECT `email`,`verify`,`sender` FROM `email_sender` WHERE `sent`='___START___' ORDER BY ABS(`id`) DESC LIMIT 1";
$execute1 = mysql_query($query1) or die("emailer.cron.php was unable to execute MySQL Query #1 on line 23 (".mysql_error().")");

/*
* Check to see if we found a match, and if not, exit the program
*/

$numrows1 = mysql_num_rows($execute1);
if ($numrows1 == 0) { exit(); }

/*
* Extract the email, verification code, and sender
* from the above start code
*/

$datarow1 = mysql_fetch_row($execute1);
$email    = $datarow1[0]; //This is the email being sent
$verify   = $datarow1[1]; //This is the verification code used to send the email
$sender   = $datarow1[2]; //This is the person who sent the original email

/*
* Check for any '___STOP___' commands with the
* same email and verification code as the 
* '___START___' code, and if found, exit the
* script
*/

$query2   = "SELECT `email` FROM `email_sender` WHERE `sent`='___STOP___' AND `email`='$email' AND `verify`='$verify'";
$execute2 = mysql_query($query2) or die("emailer.cron.php was unable to execute MySQL Query #2 on line 51 (".mysql_error().")");
$numrows2 = mysql_num_rows($execute2);
if ($numrows2 != 0) { exit(); }

/*
* We now know we are supposed to send out
* an email, first check if any emails have
* already been sent
*/

$query3   = "SELECT `sent` FROM `email_sender` WHERE `email`='$email' AND `verify`='$verify' AND `success`='1' ORDER BY ABS(`id`) DESC LIMIT 1";
$execute3 = mysql_query($query3) or die("emailer.cron.php was unable to execute MySQL Query #3 on line 62 (".mysql_error().")");
$numrows3 = mysql_num_rows($execute3);

/*
* If the above query returned 1 row, then
* we need to extract the data and get the
* number of emails that have already been
* sent out
*/

if ($numrows3 == 1) {
$datarow3 = mysql_fetch_row($execute3);
$sent     = $datarow3[0];       //Should be in the format '0-39' or '40-79'
$sent     = explode("-",$sent); //Now should be two numbers in an array (40 and 79 for example);
$sent     = $sent[1]; //The second number, for example, 79
$start    = $sent+1;  //Where we should start sending emails, for example, 80
$end      = $sent+40; //Where we are going to stop, in this case, 119
} else {
/*
 * If the above query returned 0 rows, then
 * we need to set the variables to 0;
 */
$sent  = 0;
$start = 0;
$end   = 39;
}

/*
* Now we know which addresses to get, we
* need to get those 40 emails from the 
* database
*/

$query4   = "SELECT `email` FROM `email_contacts` ORDER BY ABS(`id`) ASC LIMIT $start,40"; //Select 40 emails starting after the last email sent (Emails 80 to 119)
$execute4 = mysql_query($query4) or die("emailer.cron.php was unable to execute MySQL Query #4 on line 96 (".mysql_error().")");

/*
* Now we need to set each of those 
* emails has a Bcc(Blind Carbon Copy)
* so that other users cannot see the
* emails we are sending out to(For 
* obvious privacy reasons)
*/

$bcc = "";
while ($i = mysql_fetch_row($execute4)) {
$bcc .= "{$i[0]}\r\n";
}

/*
* Ok, now we need to compose the HTML
* for the message. Just replace the 
* below block of code with your own
* code or a plain HTML messsage. My
* code is designed for my specific 
* mass email tool
*/

/**-------------------------------------------------------VVV -REPLACE THIS WITH YOUR CODE- VVV--------------------------------------------------------------**/
$query5   = "SELECT `content` FROM `email_template` WHERE `id`=1";
$execute5 = mysql_query($query5) or die("emailer.cron.php was unable to execute MySQL Query #5 on line 122 (".mysql_error().")");
$content  = mysql_fetch_row($execute1);
$content  = $content[0];
$content  = preg_replace("/\r\n/","",$content);
$content  = preg_replace("/\n/","",$content);
$content  = preg_replace("/[\t\n\r\f\v]/","",$content);
$content  = preg_replace('/\s\s+/', ' ', $content);
$content  = preg_replace("/<!--.*?-->/", "", $content);
$content  = date("d-m-Y");
$content  = preg_replace("/(___HEAD___)/","If this message is not displaying properly, <a href=\"http://globaltrainingedge.com/newsletter/$newsl.html\">click here</a> to launch your browser.",$content);
preg_match_all("/(___CONTENT:)([A-Za-z]{1}[0-9]{1})(___)/",$content,$matches);
$count    = count($matches[2]); //Number of content areas
$i        = 0;

while ($i < $count) {
$name     = $matches[2][$i]; //The content area name
$replace  = $matches[0][$i]; //The content area id
$query6   = "SELECT `content` FROM `email_content` WHERE `name`='$name'"; //Select the content to replace it with
$execute6 = mysql_query($query6) or die("emailer.cron.php was unable to execute MySQL Query #6 on line 140 (".mysql_error().")");
$temp     = mysql_fetch_row($execute6); //Get the data we got

//Do some replacing
$temp     = preg_replace("/(___SUBEDIT___)/","",$temp);	
$content  = preg_replace("/($replace)/",$temp[0],$content); //Replace everything
$i++;
}

$query7   = "SELECT `content`,`name`,`position` FROM `email_content` WHERE `name` LIKE 'C%' ORDER BY ABS(`position`) ASC";
$execute7 = mysql_query($query7) or die("cron.emailer.php was unable to execute MySQL Query #7 on line 150 (".mysql_error().")");
while ($t = mysql_fetch_row($execute7)) {
$temp         = preg_replace("/(___EDIT___)/","",$t[0]);
$contentmain .= $temp . "<hr width=\"100%\" color=\"#CCCCCC\" style=\"margin-top:20px;margin-bottom:18px;\" />";
}

$contentmain .= $new . "<br /><br />";
$content      = preg_replace("/(___CONTENT:C___)/",$contentmain ,$content);
/**-------------------------------------------------------^^^ -REPLACE THIS WITH YOUR CODE- ^^^--------------------------------------------------------------**/

/*
* Now we need to set the headers
* with the content type and the 
* email addresses
*/

$headers = "From: wilson@globaltrainingedge.com\r\n".
	   "Reply-To: wilson@globaltrainingedge.com\r\n".
	   "MIME-Version: 1.0\r\n".
	   "Content-Transfer-Encoding: 8bit\r\n".
	   "Content-Type: text/html; charset=\"iso-8859-1\"\r\n".
	   $bcc.
	   "X-Mailer: PHP/" . phpversion();

/*
* One last preparation before 
* sending the email. We need 
* to increase the max execution
* time to prevent timeouts on 
* certain setups
*/

set_time_limit(340); //Increase script execution time to 340 seconds

/*
* Now we need to send the email,
* and if it doesn't send, log it
* do the database as a failure
* (success=0)
*/

if (!mail("","Global Training Edge - Montly Newsletter",$content,$headers)) {
//There was an error
$datetime = date("Y/m/d H:i:s");
$query8   = "INSERT INTO `email_tracker` (`email`,`sent`,`datetime`,`success`,`verify`,`sender`) VALUES ('$email','$start-$end','$datetime','0','$verify','$user')";
$execute8 = mysql_query($query8) or die("cron.mailer.php was unable to execute MySQL Query #8 on line 195 (".mysql_error().")");
echo "Sorry, but cron.emailer.php was unable to send emails $start-$end";
exit();
}

/*
* Sometimes, on certain hosting setups,
* the script will timeout at this point
* so we need to increase the max
* execution time another 20 seconds
*/

set_time_limit(20);

/*
* Sometimes depeding on the hosting
* setup, the MySQL connection will
* timeout. To prevent this, we close
* the existing connection and open a
* new one
*/

mysql_close($connection);
$connection = mysql_connect("localhost","safetyha_su","HuhAspuc4e") or die("emailer.cron.php was unable to connect to the MySQL Database on line 209 (".mysql_error().")");
$selectdb   = mysql_select_db("safetyha_webadmin",$connection) or die("emailer.cron.php was unable to select the MySQL Database on line 210 (".mysql_error().")");

/*
* The email was successful, so 
* we should log it to the database
*/

$datetime = date("Y/m/d H:i:s");
$query9   = "INSERT INTO `email_tracker` (`email`,`sent`,`datetime`,`success`,`verify`,`sender`) VALUES ('$email','$start-$end','$datetime','1','$verify','$user')";
$execute9 = mysql_query($query9) or die("emailer.cron.php was unable to execute MySQL Query #9 on line 229 (".mysql_error().")");

/*
* Now we check if all the emails
* have been sent
*/

$query10   = "SELECT * FROM `email_recepients`";
$execute10 = mysql_query($query10) or die("emailer.cron.php was unable to execute MySQL Query #10 on line 236 (".mysql_error().")");
$numrows10 = mysql_num_rows($execute10);

/*
* If all the emails have been sent,
* we should insert the '___STOP___'
* command into the database
*/

if ($numrows10 <= $end) {
//All the emails have been sent
$query5   = "INSERT INTO `email_tracker` (`email`,`sent`,`datetime`,`success`,`verify`,`sender`) VALUES (
'$email','___STOP___','$datetime','0','$verify','$user')";
$execute5 = mysql_query($query5);

//Send confirmation email
$body    = "The Mass Email has just finished sending. A total of $numrows10 emails were sent out, all of them were successful.";
$headers = 'From: webmaster@globaltrainingedge.com' . "\r\n" .
           'Reply-To: webmaster@globaltrainingedge.com\r\n' .
           'X-Mailer: PHP/' . phpversion();
mail("brandon.wamboldt@northernlightstech.com","The Mass Email Has Finished Sending",$body,$headers); //Replace my email with your own
}

/*
* The cron is finished, now we 
* will output to stdout so that
* we will receive an email from
* the cron verifying that it ran
*/

$date = date("Y:m:d H:i:s");
echo "SUCCESS[$date]: Sent emails $start-$end out. All emails were successful;";
?>

 

The script requires two databases, one for contacts, and one for the tracker

 

The tracker SQL I have below will insert a default '___START___' command. My actual program goes through a verification process

-- phpMyAdmin SQL Dump
-- version 2.11.6
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 11, 2008 at 11:38 AM
-- Server version: 5.0.45
-- PHP Version: 5.2.6

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `safetyha_webadmin`
--

-- --------------------------------------------------------

--
-- Table structure for table `email_sender`
--

CREATE TABLE IF NOT EXISTS `email_sender` (
  `id` int(11) NOT NULL auto_increment,
  `email` varchar(220) NOT NULL,
  `sent` varchar(200) NOT NULL,
  `datetime` varchar(200) NOT NULL,
  `success` varchar(1) NOT NULL,
  `verify` varchar(200) NOT NULL,
  `sender` varchar(200) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `email_sender`
--

INSERT INTO `email_sender` (`id`, `email`, `sent`, `datetime`, `success`, `verify`, `sender`) VALUES
(1, '11-07-2008', '___START___', '2008/07/11 14:37:00', '', 'verification_code_here', 'brandon');

 

Any my contact list (No data in it)

-- phpMyAdmin SQL Dump
-- version 2.11.6
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 11, 2008 at 11:39 AM
-- Server version: 5.0.45
-- PHP Version: 5.2.6

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `safetyha_webadmin`
--

-- --------------------------------------------------------

--
-- Table structure for table `email_contacts`
--

CREATE TABLE IF NOT EXISTS `email_contacts` (
  `id` int(11) NOT NULL,
  `fname` varchar(220) NOT NULL,
  `lname` varchar(220) NOT NULL,
  `email` varchar(220) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `email_contacts`
--

INSERT INTO `email_contacts` (`id`, `fname`, `lname`, `email`) VALUES
(0, 'FName', 'LName', 'username@domain.com');

Link to comment
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.