Location: PHPKode > scripts > Mail Send Addon for Drupal Simplenews Newsletter > mail_cron_job.php
<html> 
<head>
<title>Send Newsletter</title>
</head>

File version 1.1<br>This is a free script from <a href="http://tecorange.com" target="_blank">TECOrange.com</a>. If you think this is good <a href="http://tecorange.com" target="_blank">visit the page</a>, share it, subscribe to newsletter or <a href="http://www.twitter.com/tecorange" target="_blank">follow at twitter</a> to find  a lot of useful things around Web and Mobile Development, Project Management, SEO, SEM and more :-)<br /><br />For more details about this script and support <a href="http://tecorange.com/content/mail-send-addon-drupal-simplenews-newsletter" target="_blank">visit the mail send addon for drupal Simplenews newsletter page</a>.<hr />

<?php

//settings
$username_for_sending="uname"; //change this to disallow people runing this script
$password_for_sending="apass"; //change this to disallow people runing this script
$db_host="localhost"; $db_user="user"; $db_pass="pass"; $db_name="dbname"; //database connection details
set_time_limit(43200); //sets the time limit for script in case it takes time to send mails change the number within (...) , value in seconds
// you can set this to send pretty fast e.g. 100 mails every 10 seconds, set it according to your server sending limits, if any, and/or at low speed to avoid spam reporting. Rememebr to send mails only to people that want and have asked to receive.
$mail_step='20'; // how many mails to send in page refresh -every iteration 
//functions
$seconds_refresh='600'; //when sending mails you should have the window open as this page will refresh itsself to send next mails. send this to the mumber of seconds between every page refresh - iteration.
$unsubscribe_url='http://mydomain.com/unsubscribe.php'; //add the url of the users will use to unsubscribe. Do not add "/" at the end. E.g.  http://www.mysite.com/my-unsubscribe-page. Use the example in unsubscribe.php to create this page. Simplenews unsubscribe functions still work as well but we need this file since we create a new type of unsubscribe URL that is send with mails.
$use_clean_url='1'; //does your site use clean URLs or not? Does your site uses ? to access content nodes or uses something like http://www.mysite.com/my-content-node. This affects how we will create the unsubscribe URL. 1=Yes - clean URLs, 2=No we use the ? to access content nodes

function clean($str)
{
 $cleaned=strip_tags($str);
 $cleaned=htmlspecialchars($cleaned);
 $to_clean=array("%20", "\"", "'", "\\", ";", ":");
 $cleaned=str_replace($to_clean, "", $cleaned);
 return $cleaned;
}
//end of functions

$url=$_SERVER["PHP_SELF"];

if($url=="/mail_cron_job.php"){ echo"<br>In order to proceed, <b>rename this file to something other than mail_cron_job.php</b>, for extra security. Remember to update the submit form example in form.html or your custom form with your new url"; die();
}

if(!isset($_POST["uname"]) || !isset($_POST["pass"])) { echo "Wrong Unsername or Password"; die();} 

$_POST["uname"]=clean($_POST["uname"]);
$_POST["pass"]=clean($_POST["pass"]);

if ($_POST["uname"]==$username_for_sending && $_POST["pass"]==$password_for_sending){} else { 
echo "Wrong Unsername or Password"; 
die();
}

if(!isset($_GET["op"]) || ($_GET["op"]!='1' && $_GET["op"]!='2')) {echo "Wrong OP value"; die();} else {//op=1 get the mails in spool, op=2 send mails
$_GET["op"]=clean($_GET["op"]); }

if(!isset($mail_step) || $mail_step<'1' || !is_numeric($mail_step) ) {echo "Wrong STEP value. Step should be bigger than 1."; die();} else {
$mail_step=clean($mail_step); 

echo" <script type=\"text/javascript\">
var count=".$seconds_refresh.";

var counter=setInterval(formSubmitTimer, 1000);

function formSubmitTimer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
	setTimeout('document.forms.formsend.submit();', 1);
     return;
  }

document.getElementById(\"timer\").innerHTML=count + \" secs\";
}
</script>";

 echo "<body onload=\"formSubmitTimer();\">";
 }

if(!isset($_POST["footerxt"])) {echo "Wrong Footertxt not set"; die();}

$db_id = mysql_connect($db_host, $db_user, $db_pass)
 or die("Could not connect to DB.");
mysql_select_db($db_name, $db_id);


$error_mails=""; //variable used to show mail addresses that mail finction fail to process



if($_GET["op"]=='1') { 

$clean_spool_table="DELETE FROM simplenews_mail_spool";  
$result_clean_spool_table=mysql_query($clean_spool_table, $db_id);

}//if op insert 1 clean spool table before adding values 

//get first admin e-mail
$admin_mail1="select uid from users_roles where rid='3'";
$result_admin_mail1=mysql_query($admin_mail1, $db_id);
$row_admin_mail1=mysql_fetch_row($result_admin_mail1);

$admin_mail2="select mail from users where uid='".$row_admin_mail1['0']."'";
$result_admin_mail2=mysql_query($admin_mail2, $db_id);
$row_admin_mail2=mysql_fetch_row($result_admin_mail2);


if($_GET["op"]=='1') {  //if op=1
//get the newsletter to send

echo "<b>Notes before you click 'Send':</b> You should have java enabled browser.<br>You should have Drupal Simplenews newsletter module installed, and simplenews module newsletters, subscribers etc. Use a module like Elysia Cron and disable simplenews spool cron so you will not have simplenews to send mails. This is what this script will do.<br><br><b>Sender Mail that will be used:</b> ".$row_admin_mail2['0']." (this is the mail of first drupal site admin)";

$mewsletter="select * from simplenews_newsletter where status='0'";
$result_mewsletter=mysql_query($mewsletter, $db_id);
$num_rows_mewsletter=mysql_num_rows($result_mewsletter);

if ($num_rows_mewsletter<='0'){
	echo "<br><br><i>There is no newsletter to send</i>"; } else { //if there is a newsletter to send

$row_mewsletter=mysql_fetch_row($result_mewsletter);

//get the title node body and node url of newsletter node

$node_title="select title from node where nid='".$row_mewsletter['0']."'";
$result_node_title=mysql_query($node_title, $db_id);
$row_node_title=mysql_fetch_row($result_node_title);

echo "<br><br><b>Newsletter Title:</b> ".$row_node_title['0'];
echo "<br><br><b>Mail Footer Message:</b> ".$_POST["footerxt"];
echo "<br><br><b>Step:</b> ".$mail_step." messages every ".$seconds_refresh." seconds <br><i>(To change step values edit this file with a text editor and upload it again)</i>";


$node_body="select body_value from field_data_body where entity_id='".$row_mewsletter['0']."'";
$result_node_body=mysql_query($node_body, $db_id);
$row_node_body=mysql_fetch_row($result_node_body);

//select users that are subscribed to this newsletter, timestamp will be used from custom unsubscribe page
$users="select snid,tid,timestamp from simplenews_subscription where tid='".$row_mewsletter['1']."' AND status='1'";
$result_users=mysql_query($users, $db_id);
$num_rows_users=mysql_num_rows($result_users);
 
	for ($i=0; $i<$num_rows_users; $i++){
		$row_users[$i]=mysql_fetch_row($result_users);
		//get subscribed user mails
		$mails="select mail from simplenews_subscriber where snid='".$row_users[$i]['0']."' and activated='1'";
		$result_mails=mysql_query($mails, $db_id);
		$row_mails=mysql_fetch_row($result_mails);
if($row_mails['0']!='') {  //if we have a mail

   $insert_all_in_spool="insert into simplenews_mail_spool (mail, nid, tid, status,snid,data) values ('".$row_mails['0']."', '".$row_mewsletter['0']."', '".$row_mewsletter['1']."', '1', '".$row_users[$i]['0']."','".$row_users[$i]['0']."-".$row_users[$i]['1']."-".$row_users[$i]['2']."')";
 $result_all_in_spool=mysql_query($insert_all_in_spool, $db_id);
 
 

 
} //end of check if we have e-mail
	}//end of getting user mails
	if($num_rows_users<='0') { echo "<br><br><i>No users subscribed for this newsletter.</i>";} else{
		echo "<br><br><b>Spool table ready:</b> ".$i." mails added to spool<br><i>(Do not close next window until you see the message that all mails processed)</i><br><br><form action='".$url."?op=2&iteration=1' id='form1' method='POST' name='form1' ><input id='uname' name='uname' type='hidden' value='".$username_for_sending."' /> Retype Pass: <input id='pass' name='pass' type='text' value=''/> <input id='footerxt' name='footerxt' type='hidden' value='".$_POST["footerxt"]."' /><br><input id='button' name='button' type='submit' value='Send' /></p></form>"; }
		
	}//end of check if there is a newsletter to send

}//end of op=1, update spool table


  if($_GET["op"]=='2') {  //if op=2
  
 if(!isset($_GET["iteration"]) || $_GET["iteration"]<'1' || !is_numeric($_GET["iteration"]) ) {echo "Wrong ITERATION value."; die();} else {
$_GET["iteration"]=clean($_GET["iteration"]); }

  //get the newsletter to send
$mewsletter="select * from simplenews_newsletter where status='0'";
$result_mewsletter=mysql_query($mewsletter, $db_id);
$num_rows_mewsletter=mysql_num_rows($result_mewsletter);


if ($num_rows_mewsletter<='0'){
	echo "<br><br><i>There is no newsletter to send</i>"; } else { //if there is a newsletter to send

$row_mewsletter=mysql_fetch_row($result_mewsletter);

//get the title node body and node url of newsletter node

$node_title="select title from node where nid='".$row_mewsletter['0']."'";
$result_node_title=mysql_query($node_title, $db_id);
$row_node_title=mysql_fetch_row($result_node_title);

$node_body="select body_value from field_data_body where entity_id='".$row_mewsletter['0']."'";
$result_node_body=mysql_query($node_body, $db_id);
$row_node_body=mysql_fetch_row($result_node_body);

//select the users that they have not receive the newsletter first
$users="select snid,data from simplenews_mail_spool where status='1' LIMIT 0,".$mail_step;
$result_users=mysql_query($users, $db_id);
$num_rows_users=mysql_num_rows($result_users);
 
	for ($i=0; $i<$num_rows_users; $i++){
		$row_users[$i]=mysql_fetch_row($result_users);
		//get subscribed user mails
		$mails="select mail from simplenews_subscriber where snid='".$row_users[$i]['0']."' and activated='1'";
		$result_mails=mysql_query($mails, $db_id);
		$row_mails=mysql_fetch_row($result_mails);
if($row_mails['0']!='') {  //if we have a mail

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$row_admin_mail2['0'].' <'.$row_admin_mail2['0'].'>' . "\r\n";

if ($use_clean_url=='1') $unsubscribe_url_sign='?'; else $unsubscribe_url_sign='&';

if( mail($row_mails['0'],$row_node_title['0'], $row_node_body['0']."<br>----<br>To unsubscribe visit ".$unsubscribe_url.$unsubscribe_url_sign."checkcode=".$row_users[$i]['1']."<br>----<br>".$_POST["footerxt"], $headers )) { $update_spool="update simplenews_mail_spool set status='2' where snid='".$row_users[$i]['0']."'";
 mysql_query($update_spool, $db_id); } else {
	$update_spool="update simplenews_mail_spool set status='2', error='1' where snid='".$row_users[$i]['0']."'";
 mysql_query($update_spool, $db_id); 
 
 $error_mails=$error_mails.$row_mails['0']."<br>";
 }
 

 
} //end of check if we have e-mail
	}//end of getting user mails
	}//end of check if there is a newsletter to send
	
	//check if all mails processed
$check_if_all_processed="select snid from simplenews_mail_spool where status='1'";
$result_check_if_all_processed=mysql_query($check_if_all_processed, $db_id);
$num_rows_check_if_all_processed=mysql_num_rows($result_check_if_all_processed);

	if ($num_rows_check_if_all_processed<='0') { //all mails sent
   
   
   $mails_processed="select * from simplenews_mail_spool";
$result_mails_processed=mysql_query($mails_processed, $db_id);
$num_rows_mails_processed=mysql_num_rows($result_mails_processed);
echo "<br><br>All Mails (".$num_rows_mails_processed.") Processed.";

if ($error_mail!=""){ echo "<br><br>The following mails did not sent:<br>".$error_mail; } else{ echo "<br><br><i>No mail errors found when sending (php mail function didn't return errors)</i><br>";}

   $clean_spool_table="DELETE FROM simplenews_mail_spool";  
   $result_clean_spool_table=mysql_query($clean_spool_table, $db_id);
   
    $update_newsletter_status="update simplenews_newsletter set status='2', sent_subscriber_count= '".$num_rows_mails_processed."' where nid='".$row_mewsletter['0']."'";
$result_update_newsletter_status=mysql_query($update_newsletter_status, $db_id);

   }else{
	   

	   echo"<br><br><i>Do not close this window until all mails send. This page will automatically refresh its self.<br><br></i><b>Iteration Count:</b> ".$_GET["iteration"]."<br><br><b>Next Iteration in about:</b> <span id='timer'></span> <br><br><b>Remaining E-mails:</b> ".$num_rows_check_if_all_processed."<br><br><form action='".$url."?op=2&iteration=".($_GET["iteration"]+1)."' id='formsend' method='POST' name='formsend' ><input id='uname' name='uname' type='hidden' value='".$username_for_sending."' /><input id='pass' name='pass' type='hidden' value='".$password_for_sending."'/> <input id='footerxt' name='footerxt' type='hidden' value='".$_POST["footerxt"]."' /><br></p></form>";
   }
   
 }//end of op=2, send mail

?>

</body></html>
Return current item: Mail Send Addon for Drupal Simplenews Newsletter