I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code. It is only working when I specify a single e-mail address, however, I need to have them query my database and send the e-mail to each e-mail address. Where am I going wrong here?
function sendmail($cat, $user) {
require_once "Mail.php";
$elist = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
$elist = mysql_fetch_array($elist);
$from = "EMAIL ADDRESS";
$to = $elist;
$subject = "SUBJECT";
$body = "BODY";
$host = "smtp.domain.com";
$username = "USERNAME";
$password = "PASSWORD";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
Try something like this but one point to note is that you should send emails individually ratehr than group all your email addresses in one "to" field. Other users might not like others seeing that. Maybe your smtp function breaks down the array, not sure :-|
function sendmail($cat, $user)
{
require_once "Mail.php";
$elist = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
$from = "EMAIL ADDRESS";
$subject = "SUBJECT";
$body = "BODY";
$host = "smtp.domain.com";
$username = "USERNAME";
$password = "PASSWORD";
if(mysql_num_rows($elist) > 0)
{
while($elist_result = mysql_fetch_array($elist))
{
$headers = array ('From' => $from,
'To' => $elist_result['cEmail'],
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
}
}
mysql_fetch_array fetches an array with entries corresponding to each of the columns of a single row of your table. In other words, here it's an array containing one user's cEmail column.
You need to fetch all the values into a single array before calling the mail functions. You could do it like this:
$dest = array();
while ($arr = mysql_fetch_array($elist)) {
$dest[] = $arr['cEmail'];
}
I had a similar issue while trying to loop though my recipients' database table with the aim of sending personalized PEAR emails to each recipient.
The problem I encountered was that the loop would cease after one iteration until I amended $recipients to just send the first item in the array, as illustrated in this code snippet. ($recipients is an array of IDs for recipients):
/*PEAR mail set-up code included here*/
for ($i = 0; $i < count($recipients); $i++) {
$sql_recipients = "SELECT * FROM $data_table WHERE id = $recipients[$i] ORDER BY id ASC ";
$res_recipients = mysqli_query($mysqli,$sql_recipients)
or die (mysqli_error($mysqli));
$recipients_info = mysqli_fetch_array($res_recipients);
$recip_id = $recipients_info['id'];
$recip_organisation = $recipients_info['organisation'];
$recip_fname = $recipients_info['fname'];
$recip_lname = $recipients_info['lname'];
$recip_email = $recipients_info['email'];
/*PEAR mail code here */
$recipients[0] = $recip_email;
$mail->send($recipients[0], $hdrs, $body);
}
I learned to this from one of the examples in the book I am learning PHP from, Head First PHP & MySQL.
What you can do is send each e-mail individually, but simultaneously, through a while loop. With a mysqli_query selecting the e-mails, make a while loop that goes through my
while ($row_data = mysqli_fetch_array($your_query_in_a_variable)) {
// Then you will set your variables for the e-mail using the data
// from the array.
$from = 'you#yoursite.com';
$to = $row_data['email']; // The column where your e-mail was stored.
$subject = 'Open Me!';
$msg = 'Hello world!';
mail($to, $msg, $from);
}
I hope that is clear. You basically just call the rows you want in your query, then use mysqli_fetch_array, which goes through each row every time it is called (someone correct me, if wrong) and will exit when there are no more rows left that were called.
My suggestion would be use the php mail() function and set the smtp server parameters in your php.ini file.
Then all you have to do is query your db, pull the first record out as your to address and then loop through the result set and put each email address into an array. Then just use the join function to join the array with commas and use it as the BCC for the header string.
Here is what I would use if possible. I've included a couple notes as //comments
function sendmail($cat, $user) {
$result = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
//pull out first email as the to address
$to = mysql_fetch_array($result);
//create array to store all the emails
$elist = array();
//loop through and put each email into an array
// you might be able to skip this altogether if you can just join $result
// but I'm to lazy to investigate what all is being returned
while($row = mysql_fetch_assoc($result)){
$elist[] = $row['cEmail'];
}
//join the emails into a comma separated string
$bcc = join($elist, ",");
$from = "EMAIL ADDRESS";
$subject = "SUBJECT";
$body = "BODY";
$headers = "From: ". $from ."\r\n";
$headers .="BCC: ". $bcc ."\r\n";
mail($to, $subject, $body, $headers);
}
Hopefully this is useful information.. Feel free to pick it apart and use whatever you may need, like if you can use part to implement your Mail class.
You schould not use the php mail() function. It is dead slow because it does a full connect to the smtp server every single mail you send.
A good Mail library such as Zend_Mail connects only once and delivers the mails in one batch to the smtp server.
You should also not send all your mails via a long BCC-Line. At least if you want your email not marked as spam (See this Question and this Blog-Entry by Jeff).
<?php
function sendmail($cat, $user) {
// Setup mailer
require_once "Mail.php";
$smtp = Mail::factory('smtp', array(
'host' => "smtp.domain.com";
'auth' => true,
'username' => "USERNAME";
'password' => "PASSWORD";
));
// ALWAYS escape your variables!
$query = sprintf("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%s'",
mysql_real_escape_string($cat),
// submit the query
$result = mysql_query($query);
// iterate over each row
while ($row = mysql_fetch_assoc($result)) {
$from = "EMAIL ADDRESS";
$to = $row['cEmail'];
$subject = "SUBJECT";
$body = "BODY";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
// Send mail with individual to-address via smtp
$mail = $smtp->send($to, $headers, $body);
}
}
Use this code to resolve your problem.
//Connect to database
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$sql = "SELECT email FROM members";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res) )
{
$area .= $row['email']. ", ";
}
// read the list of emails from the file.
$email_list = explode(',', $area);
// count how many emails there are.
$total_emails = count($email_list);
// go through the list and trim off the newline character.
for ($counter=0; $counter<$total_emails; $counter++)
{
$email_list[$counter] = trim($email_list[$counter]);
}
$to = $email_list;
echo $to;
Related
I have PHP Send Email using SMTP.
$from = "Info <donotreply#test.com>";
$subject = "Calibration will be expiring!";
$body = 'Hello';
$to = "david#test.com, dono#test.com";
$cc = "rena#test.com";
$bcc = ""; //sometimes BCC can be empty
$host = 'smtp.test.com';
$port = '587';
$username = 'donotreply#test.com';
$password = 'dontreply?';
$headers = array(
'Port' => $port,
'From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8',
'Cc' => $cc
);
$recipients = $to.", ".$bcc.", ".$cc;
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($recipients, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
I tried to run above code and only working if $bcc is not empty.
Error when $bcc is empty
Failed to add recipient: #localhost [SMTP: Invalid response code received from server (code: 501, response: 5.1.3 Invalid address [HKXPR02MB0695.apcprd02.prod.outlook.com])]
Is there any way how to fix it or need some modification there?
If $bcc variable is empty then your concatenated string contains ,, which is syntactically incorrect. You need to add some logic there to make ensure this is not happening.
Also I doubt you set BCC correctly anyway. It should not be just another recipient like you have now.
I've got the solution below:
$bcc = $dEmailListBCC['EMAIL_ADDRESS'];
if($bcc == "")
{
$a = "";
}
else
{
$a = ",".$bcc;
}
First, check the $bcc variable is empty or not.
and then the recipients to be like this:
$recipients = $to." ".$a.", ".$cc;
I have a contact form and I want to receive message through mail and simultaneously send mail to the client. I have the below code it works some times. That is some times I get the message and client also get the message but sometimes only one email is sent either to client or to me but never both all the time.
I have seen example in the following link https://teamtreehouse.com/community/how-to-send-two-different-email-with-different-bodies-using-phpmailer but it uses PHP Mailer I want the same functionality but by using PEAR Mail.
I have seen other similar question over here PEAR Mail using gmail SMTP won't send 2 emails in sucession but the answer given in that question doesn't solve my problem
Below is the code which works some time.
<?php
require_once('Mail.php');
require_once('Mail/mime.php');
if (isset($_POST['Captcha'])) {
$name = filter_var($_POST['Name'] , FILTER_SANITIZE_STRING);
$email = filter_var($_POST['Email'] , FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['Phone'] , FILTER_SANITIZE_STRING);
$budget = filter_var($_POST['Budget'] , FILTER_SANITIZE_STRING);
$timeline = filter_var($_POST['Timeline'] , FILTER_SANITIZE_STRING);
$description = filter_var($_POST['Description'] , FILTER_SANITIZE_STRING);
$spam = filter_var($_POST['usernameoftest'] , FILTER_SANITIZE_STRING); // Bot trap
if($spam)
{ // If the hidden field is not empty, it's a bot
die("No spamming allowed bitch!");
} else {
$from = "sales#ganeshghate.com";
$to = "ganeshghate#hotmail.com";
$subject = "Message from : ".$name;
$body = "Client's Name : ".$name."\r\n";
$body .= "Client's Email ID : ".$email."\r\n";
$body .= "Client's Phone Number : ".$phone."\r\n";
$body .= "Client's Budget : ".$budget."\r\n";
$body .= "Client's Timeline : ".$timeline."\r\n";
$body .= "Client's Message : ".$description."\r\n";
$host = "myhost";
$port = "myport";
$username = "myusername";
$password = "mypassword";
$crlf = "\n";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$mime = new Mail_mime($crlf);
$mime->setTXTBody($body);
$body = $mime->get();
$headers = $mime->headers($headers);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
$output["errorclientemail"] = "<div>
<h2 class='error'>".$mail->getMessage().$mail->getUserInfo()."</h2>
<h2>Oops there was some error we have not received your message</h2>
<h2>Please report the above error to us via skype , email , phone details are on the left side</h2>
</div>"."\r\n";
} else {
$output["successclientemail"] = "Thank you we will get back to you soon";
}
$bodyback = "We have received your message :".$body."\r\n";
$bodyback .= "We will get back to you soon"."\r\n";
$bodyback .= "With Regards "."\r\n";
$bodyback .= "Ganesh Ghate "."\r\n";
$subjectback = "Thank You for contacting us";
$headersreply = array ('From' => $from,
'To' => $email,
'Subject' => $subjectback);
$crlf1 = "\n";
$mime = new Mail_mime($crlf1);
$mime->setTXTBody($bodyback);
$bodyback = $mime->get();
$headersreply = $mime->headers($headersreply);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email, $headersreply, $bodyback);
if (PEAR::isError($mail)) {
$output["errorreplyemail"] = "<div>
<h2 class='error'>".$mail->getMessage().$mail->getUserInfo()."</h2>
<h2>Oops there was some error we have not delivered confirmation email to you</h2>
<h2>Please report the above erorr to us via skype , email , phone details are on the left side</h2>
</div>"."\r\n";
} else {
$output["successreplyemail"] = "We have sent confirmation email to you. Please check your inbox / junk mail";
}
echo json_encode($output);
}
}
?>
Thanks in advance
I'm attempting to BCC to a list of subscribers from a database, using PHP mail(). Everything works, but I'm running into a problem that has troubled me all morning. I'm able to send the list with BCC, but are unable to append the receiving end email address to the deader "To:".
For example, I send the list to the following email addresses (test1#example.com, test2#example.com, and test3#example.com). Each email address receives an email and the other email addresses are hidden because of BCC.
My problem is that in the header, "To:" is displayed blank on all of the receiving ends of the list. That I understand and know that header won't display because I have only the BCC header within the outgoing message. I've attemted to for loop the process but I receive all of the emails, plus one for that address in one loop.
Here is my working code: The working code includes the loop that I attempted for solving the To: header. I'm able to send the email, though I receive all of the emails that were sent.
<?php
/*
Gathers the number of rows within the database. Used for the loop that displays the entire list in the BCC.
*/
session_start();
include_once '../dbconnect.php';
$result = mysql_query("SELECT * FROM news");
$num_rows = mysql_num_rows($result);
$rows = $num_rows;
/*
Requests the list from the database, please the list in a loop, displays the list only once, and places list in an operator.
*/
$result = mysql_query("SELECT * FROM `news`");
while($row = mysql_fetch_array( $result )) {
for ($x = 1; $x <= 1; $x++) {
$contacts.= "".$row['email'].",";
}
}
/*
ATTEMPT (It works... sort of): Sends mail to the list using BCC, displays the ONLY receivers email address in the To: header
*/
$result = mysql_query("SELECT * FROM `news`");
while($row = mysql_fetch_array( $result )) {
for ($x = 1; $x <= 1; $x++) {
$receiver= "".$row['email']."";
$to = "$receiver";
$subject = 'Test Email';
$headers = "From: example#example.com\r\n";
$headers .= "BCC: $contacts";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<h1 style="">Test Message</h1>';
$message .= '</body></html>';
mail($to,$subject, $message, $headers);
}
}
?>
My general thought was to loop, but I can't find a solution that actually solves this completely, by BBC to the list and displaying only the receiving ends email address in the To: header. Any thoughts or ideas?
Update with SMTP Server
I've been attempting to use the solution found in this thread and apply it to an SMTP server. Send the message using SendGrid was the ideal choice. I've come up with the below option, but the script only seems to send one message to one of the addresses in the database and not all the address.
<?php
require_once "Mail.php";
$sub = $_POST['subject'];
$ttl = $_POST['title'];
$img = $_POST['image'];
$bdy = $_POST['body'];
$lk = $_POST['link'];
mysql_connect("", "", "") or die(mysql_error()) ;
mysql_select_db("") or die(mysql_error()) ;
$result = mysql_query("SELECT `email` FROM news");
$num_rows = mysql_num_rows($result);
$receivers = array();
while ($row = mysql_fetch_array($result)) {
$receivers[] = $row['email'];
}
foreach ($receivers as $receiver) { }
$from = "test#example.com";
$to = $receiver;
$subject = $sub;
$mime = "1.0";
$ctype = "text/html; charset=ISO-8859-1";
$body = '
<html><body>
<p>Test Message!</p>
</body></html>
';
$host = "";
$port = "";
$username = "";
$password = "";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'MIME-Version' => $mime ,
'Content-Type:' => $ctype);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
The code includes some general improvements to your code. I have added inline comments to explain what I have done.
<?php
// General thing: If you do not need a session, do not start one ;)
session_start();
include_once '../dbconnect.php';
// Select only what you really need from the table. This saves you memory
// and it speeds up the query.
$result = mysql_query("SELECT `email` FROM news");
// You are not using these numbers in the script you showed us. I am just
// leaving them in here to show you, how you can reuse the "$result"
// variable without querying the database again.
$num_rows = mysql_num_rows($result);
// We are reusing the "$result" here without re-querying the database, which
// speeds the whole process up and takes load away from the database. We are
// storing all receivers in a dedicated variable, to reuse them later on.
$receivers = array();
while ($row = mysql_fetch_array($result)) {
$receivers[] = $row['email'];
}
// Now, instead of querying the database again, we are using our stored mail
// addresses in "$receivers" to send the emails one by one. We could have
// done this part in the "while" loop before, but I wanted to stay close to
// your code, so you would recognize it ;)
foreach ($receivers as $receiver) {
// I have removed the "for" loop here, because it runs only once. If a loop
// only runs once and you control all its input, you really do not need a
// loop at all (except some exceptions, just in case someone knows one^^).
// You can actually just put the value of $receiver in $to. PHP is pretty
// good at typecasting of scalar types (integers, strings etc.), so you do
// not need to worry about that.
$to = $receiver;
$subject = 'Test Email';
// I am putting the headers into an array and implode them later on. This
// way we can make sure that we are not forgetting the new line characters
// somewhere.
$headers = array(
"From: example#example.com",
"MIME-Version: 1.0",
"Content-Type: text/html; charset=ISO-8859-1",
// I have removed the "BCC" header here, because this loops send out an
// email to each user seperately. It is basically me sending an email to
// you. Afterwards I copy&paste all the content to another new mail and
// send it to another fella. You would never know that you both got the
// same mail ;)
);
$message = '<html><body>';
$message .= '<h1 style="">Test Message</h1>';
$message .= '</body></html>';
// Imploding the headers.
$imploded_headers = implode("\r\n", $headers);
mail($to, $subject, $message, $imploded_headers);
}
This code basically send out one email at a time. No one who receives such an email knows which email addresses the email went to.
As mentioned in the code, this snippet can be further optimized. Since email sending itself is a pretty difficult area, I would really suggest that you find some PHP library that bundles that whole thing and work with it. You can make so many mistakes with the whole email sending thing, that I would not run a script like that in production if you do not want to get marked as spam soon after.
Add \r\n to:
$headers .= "BCC: $contacts\r\n";
Each header must be on new line.
I am facing quite strange issue, I've php script which sends out an email to the list of users containing HTML table(with the data) and CSV attachment of the same data. The problem is when that script to send out more then 10 emails, in some of the emails we get
--=_f3be233a9b22e88524e1539166c49be0 Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=UTF-8
in email body and HTML table lost the formatting as well, however CSV data is absolutely fine in that email.
Basically the purpose of the script is to pick the data according to user subscribe information(database-table) and send it to the subscribe user early morning. Every night the database tables are updated with the new data, which is picked up by that PHP script and send in an email. Further that PHP script trigger by Windows Schedule task.
Below is the code of the application.
if($ix>0)
{
while(odbc_fetch_row($subRes2))
{
$s_email=odbc_result($subRes2, 1);
//echo $s_email;
$from = "Sender <alerts#xxx.com>";
$to = "$s_email";
$subject = "Information_DB:" . $arrayE . " Restored on: " . "-";
$host = "xxxinternal.xxxx.com";
$port = "25";
//disabled the username and password because currently sending unauthenticated email.
// $username = ""; //<> give errors
//$password = "";
//add the email headers 29082013 1008 - SMS
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8');
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => false));
//'username' => $username,
//'password' => $password));
$subject = "Results from query";
$crlf = "\n";
$mime_params = array(
'text_encoding' => '7bit',
'text_charset' => 'UTF-8',
'html_charset' => 'UTF-8',
'head_charset' => 'UTF-8'
);
// Creating the Mime message
$mime = new Mail_mime($crlf);
// Setting the body of the email
//$mime->setTXTBody($body);
$mime->setHTMLBody($body);
$file='./wamp/www/' . $csv_filename;
$mime->addAttachment($csv_filename,'application/octet-stream');
$body = $mime->get($mime_params);
$headers = $mime->headers($headers);
// Sending the email
// $mail =& Mail::factory('mail');
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
// echo "<script>window.close()</script>";
}
else {
echo("<p>Message successfully sent!</p>");
}
}}}
else
{
$from = "Sender <alert#xxx.com>";
$to = "$s_email";
$subject = "Information_DB:" . $arrayE . " Restored on: " . "-";
//$host = "ssl://smtp.gmail.com";
$host = "xxxinternal.xxxx.com";
$port = "25";
//disabled the username and password because currently sending unauthenticated email.
// $username = ""; //<> give errors
//$password = "";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8');
?>
Unfortunately when we tested I could't seen this issue. But when its went UAT lots of user get this issue and it seems to be consistent with the database. For e.g. if user A is subscribe with Spain and Russian data, then consistently they experience the issue with Russian Data email (contains the mentioned headers in the email) however Spain data email is fine. In the live its probably sending around 100's of email daily.
I will appreciate if any of you please point me out what is going wrong as I am setting up the UTF-8 character set in an email mime setup but still getting this issue.
Regards
Shoaib
Most probably you are sending emails too fast that may occur in the result of spam/unwantd email use sleep(4) to create the 4 sec delay in next `mail.
The problem was with mime type, which require to code again. Basically the message I was sending was not encoded with UTF-8 which I did. This time I user Mail_mimePart instead of Mail_mime and it works treat.
That example was very very helpful
---ahttp://tiger-fish.com/comment/reply/133---
and some of the parameter explanation for Mail_mimePart can be found on below link
ahttp://pear.php.net/manual/en/package.mail.mail-mimepart.mail-mimepart.php---
How to attach the attachment using Mail_mimePart.
ahttp://pear.php.net/manual/en/package.mail.mail-mimepart.addsubpart.php---
Hope it helps.
I use the code below to send email to many people from my database but it usually timeouts and does not send to all. Please tell me how can i set it in php so that it sends like only 1000 email per 10mins in php?
require_once "Mail.php";
$from = "xxx Support <$sender>";
$to = "$to";
$subject = "$subject";
$body = "Dear $fname,\n\n$note\n\n\nYou are getting this email because you registered on our website www.xxx.com and agreed to our Terms and Conditions which includes to receive email from us at any time to your email address $to.";
$host = "smtp1.xxx.net";
$username = "no_reply#xxx.net";
$password = "4t46546$##?";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
}
// Show sent emails.
echo "$row[fname] $row[lname] ($row[email])<br>";
}
You can modify your script to pull recipients starting from a certain number, and until all recipients are served, output a META redirect to force the browser to reload from where it left off.
Imagine:
<?php
// Start from $x, or zero if no $x
$x = ( isset( $_REQUEST['x'] ) ? $_REQUEST['x'] : 0 );
// Count total number of recipients
$rs = mysql_query('SELECT COUNT(*) AS total FROM recipients ');
if ( $rs ) $row = mysql_fetch_assoc( $rs );
$total = $row['total'];
// Pull recipients $x through $x+1000 from database
$rs = mysql_query('SELECT * FROM recipients ORDER BY email ASC LIMIT ' . $x . ', 1000 ' );
// Count number of recipients in query result set
$num_recipients = mysql_num_rows( $rs );
while ( $row = mysql_fetch_assoc( $rs ) ){
// Send the message here...
}
if ( ( $num_recipients + $x) < $total ){
// We've not yet reached the total # of recipients
// Output the meta redirect to start from ($x+1000).
echo '<meta http-equiv="REFRESH" content="0;url=this-script.php?x=' . ($x+1000) . '">';
} else {
// We've finished, do something...
}