1

I have database of 1000 members, which contains email ids of users and had developed code for sending mails to all users in database using single administrator account - the administrator logins were hardcoded in the code.

Now I would like to take it to next level where all the logins of admin would be stored in another database and code would read the login from database and would send mails. eg code would send mails to user#1-50 using admin#1 login and send mails to user#51-100 using admin2 logins and so on.

below is the code which I am trying, and it seems that there is some problem with multiple loops. Can someone help please.

<?php
error_reporting(E_ALL);
//error_reporting(E_STRICT);
ini_set("display_errors", "on");
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
ini_set('memory_limit', '6500M'); //Maximum amount of memory a script may consume (128MB by default)
date_default_timezone_set('UTC');

require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail                = new PHPMailer();
$body                = file_get_contents("contents.html");
$body                = preg_replace('/[\]/','',$body);

$mail->IsSMTP();        
$mail->Host          = "ssl://smtp.gmail.com";
$mail->SMTPAuth      = true;
$mail->SMTPKeepAlive = true;
$mail->Port          = 465;
$mail->Subject       = "Subject";
$mail->AddReplyTo ('example@domain.com', 'test');

$mail->body         = $body;
$mail->AltBody      = "To view the message, please use an HTML compatible email viewer!";
$mail->IsHTML(true);
$mail->MsgHTML($body);

$con = mysql_connect("localhost","root","password");
if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
mysql_select_db("test") or die(mysql_error()); //Databasename

$query1  = "SELECT * FROM loginids WHERE Count >= 1"; //count is column name in table loginids
$result1 = mysql_query($query1) or die(mysql_error());
$row1    = mysql_fetch_array ($result1);

$Counter = 1;
$startnum1 = 0;
$endnum1 = 0;

while ($Counter <= 3) { 

 $mail->Username    = $row1["UserName"]; 
 $mail->Password    = $row1["Password"]; 
 $mail->From        = $row1["UserName"];
 $mail->FromName    = $row1["FromName"];

 $startnum1 = $endnum1;
 $endnum1   = $startnum1 + 2;

 $query2    = "SELECT EmailID FROM dummy Limit $startnum1,$endnum1";
 $result2   = mysql_query($query2) or die(mysql_error());

        while ($row2 = mysql_fetch_array ($result2)) {
            $mail->AddAddress($row2["EmailID"]);
          //$mail->AddStringAttachment($row["EmailID"], "contents.html");

          if(!$mail->Send()) {
            echo "Mailer Error (" . str_replace("@", "&#64;", $row2["EmailID"]) . ') ' . $mail->ErrorInfo . '<br />';
          } else {
            echo "Message sent From : " .$row1["UserName"]." Message sent to :" . $row2["EmailID"] . ' (' . str_replace("@", "&#64;", $row2["EmailID"]) . ')<br />';
          }
          $mail->ClearAddresses();
        }
$Counter++;     
}
?>

Hi Guys, Thanks for your valuable feedback much appreciated. I am still learning and seems theres lot of thing to do.. I have updated my code (above) accordingly and still not able to send out mails.. I am not sure if I am using the loops correctly.. so heres what I am trying to do in the code.. I would like to send (say) 50 mails using each account.. I have 3 email accounts and $Counter is checking my account number. And startnum1/endnum1 is for no of emails each account should send.

so $startnum1, $endnum1 should also be changed dynamically for each account #.
for e.g.  
account#1, $startnum1=1, $endnum1=50
account#2, $startnum1=51, $endnum1=100
and so on..

Now when I am trying this code I am getting "Mailer Error (recipient at domain.com) The following From address failed: sender1 at gmail.com : Called Mail() without being connected"

BackBencher
  • 61
  • 1
  • 1
  • 7
  • you do know that `mysql_connect` (which by the way is deprecated along with all other `mysql_`* functions and should not be used with new code) should be in lowercase, right (same with `mysql_query`)? PHP is case sensitive. – Nick Andriopoulos Apr 19 '13 at 19:46
  • 1
    Your code seams incomplete..... where is startnum1 and $endnum useed. and what is $mail->Username; $mail->Password; $mail->From; $mail->FromName; doing? – Lylo Apr 19 '13 at 19:49
  • "(" and ")" are pointless around $row['something']; – Jonast92 Apr 19 '13 at 19:58
  • @Lylo $mail->Username; $mail->Password; $mail->From; $mail->FromName should be $mail->$Username; $mail->$Password; $mail->$From; $mail->$FromName.. and even if I ignore/remove startnum and endnum from code (for moment) it is not working.. – BackBencher Apr 19 '13 at 20:02

2 Answers2

4

You've got bad queries. Nowhere do you define $startnum1 and $endnumb1, so the inner query becomes:

SELECT emailid FROM dummy Limit ,
                               ^^^--syntax error

Since you have absolutely NO error handling in your code, and simply assume success at each stage, no wonder you can't find out why things are failing.

At bare minimum, your query calls SHOULD be something like

$result = mysql_query($sql) or die(mysql_error());
                          ^^^^^^^^^^^^^^^^^^^^^^

NEVER suppress errors with @, and NEVER ignore return values. This is a kajillion times MORE applicable when you've got obvious problems.

Your code is the equivalent of stuffing your fingers in your ears and going "lalala can't hear you" and ignoring everything MySQL could possibly do to help you figure out the problem.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

A few things that comes to mind when reading you're code.

  • You're making an iteration 4 times of sending mails to each and every login. Is this what you want? (for ($Counter = 0; $Counter <= 4; $counter += 1) {)

  • You're suppressing errors with @ so you don't actually know when there is an error or not. In your case: With @mysql_select_db("test"); you don't even know if you're connected to a database that exists (because errors are ignored). Type like mysql_select_db("test") or die(mysql_error());

  • You have uneccessary paranthesis: I believe $Username = ($row1["UserName"]); works, but it's enough to type $Username = $row1["UserName"];

  • Incorrect assignments? of values:

I guess with:

 $Username   = ($row1["UserName"]); 
 $Password   = ($row1["Password"]); 
 $From       = ($row1["UserName"]);
 $FromName   = ($row1["FromName"]);

 $mail->Username; 
 $mail->Password; 
 $mail->From;
 $mail->FromName;

Your're trying to do:

 $Username   = $row1["UserName"]; 
 $Password   = $row1["Password"]; 
 $From       = $row1["UserName"];
 $FromName   = $row1["FromName"];

 $mail->Username = $Username;
 $mail->Password = $Password;
 $mail->From = $From;
 $mail->FromName = $FromName;
  • Non assigned values

    $query2 = "SELECT emailid FROM dummy Limit $startnum1,$endnum1";

should be something like

$startnum1 = 0;
$endnum1 = 99;
$query2     = "SELECT emailid FROM dummy Limit $startnum1,$endnum1"; 

else the query would fail.

Taking a look at this block of code:

  $mail->body       = $body;
  $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
  $mail->IsHTML(true);
  $mail->MsgHTML($body);

it seems like you could use above outside of all the loops (else same values are defined a lot of times)

  $mail->AddAddress($row2["emailid"], $row2["emailid"]);

You're adding id's instead of actual mailadresses (it seems like that anywway)

$mail->AddAddress($row2["emailid"], $row2["emailid"]);

And besides from that you're adding the same "emailid" twice.

Mysql-functions should not be used, because functions are deprecated and will soon be removed from php. Use PDO or mysqli instead.

I hope above will help you in right direction.

bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72