Forum Moderators: coopster

Message Too Old, No Replies

php mail() multiple recipients

         

PartisanEntity

11:32 am on Jan 7, 2010 (gmt 0)

10+ Year Member



Hello all,

I am having issues trying to write a simple newsletter script, this is what I have so far:

<?php
//get the variables
$subject = $_POST['nform_newsltitle'];
$message = $_POST['nform_newsltext'];
$recipients = $_POST['nform_newslrecipients'];
$email = "contact@example.com";

//if ALL and SPECIFIC users have been selected, go back to the form with an error
if ($recipients[0] == "ALL" && strlen($recipients[1]) > 1) {

$link = 'Location: index.php?page=writenewsletter&newsl_error=1&newstitle='.$title.'&newsltext='.$text;
header($link);

} else {

//include our db data to make the connection
include ('db.php');

if ($recipients[0] == "ALL") {

$content1 = mysql_query("SELECT email FROM users WHERE newsletter = 1");

while($row = mysql_fetch_array($content1))
{
$to = $row['email'].',';
echo $to;
}

} else {

}

mail($to,$subject,$message,"From: ".$email.""); //a very simple send
?>

But it's only sending one email and ignoring the other recipients.

Any experienced users know what I am doing wrong?

Thank you!

dreamcatcher

1:45 pm on Jan 7, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You are overwriting the variable with each loop, so it will only be populated with the last address. Try:


$addresses = array();
while($row = mysql_fetch_array($content1))
{
addresses[] = $row['email'];
}

and then:

if (!empty($addresses)) {
mail(implode(',',$addresses),$subject,$message,"From: ".$email."");
}

dc

Psychopsia

5:21 pm on Jan 7, 2010 (gmt 0)

10+ Year Member



Or add a dot in this line, just before =, as:

$to .= $row['email'].',';

PartisanEntity

5:32 pm on Jan 7, 2010 (gmt 0)

10+ Year Member



Thanks guys.

I like the concatenation idea, so I went ahead with that.

Working.

dreamcatcher

6:03 pm on Jan 7, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



On some servers the extra , would trigger an e-mail to nobody, so you might want to strip that.

dc

Psychopsia

6:53 pm on Jan 7, 2010 (gmt 0)

10+ Year Member



The case dreamcatcher mentions, can be avoided by:

$to = '';
while($row = mysql_fetch_array($content1))
{
$to .= (($to != '') ? ', ' : '') . $row['email'];
echo $to;
}

PartisanEntity

8:29 pm on Jan 7, 2010 (gmt 0)

10+ Year Member



actually i used rtrim($to, ",") to get rid of the last ','

Psychopsia

8:58 pm on Jan 7, 2010 (gmt 0)

10+ Year Member



Also as my previous post, you should add:

$to = '';

To initialize $to before "while(" to avoid notice error if error_reporting is configured on server.