...

View Full Version : php mail() multiple recipients



partisanentity
01-07-2010, 11:26 AM
Hello all,

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


//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!

partisanentity
01-07-2010, 11:29 AM
I seem to have posted this in the wrong subforum. Can a mod move it for me please? Thanks!

Fou-Lu
01-07-2010, 12:51 PM
You keep overwriting the $to:


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

Concat the $to variable using $to .= $row['email'] . ',';. You may want to consider stripping the last ',' as well with rtrim($to, ',');

partisanentity
01-07-2010, 01:34 PM
Thanks that got it to work.

Now I have another issue. Using the form that I created it is possible to send either to ALL or to specific recipients.

If sending to ALL, then the above code works nicely.

But in the case of select recipients I have not figured out a way to go through the array and select one recipients email at a time, add it to the $to and then continue going through the array until its finished.

This is what I have been trying, but it's not working:



for ( $i=0; $i < count($recipients); $i++ ) {

$prename = $recipients[$i];

$content = mysql_query("SELECT email FROM users where username=$prename");

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

}

Any ideas ?

sir pannels
01-07-2010, 02:22 PM
$selected_addrs = array('me@hotmail.com','you@gmail.com','him@this.com');

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


Good luck :)

JAY6390
01-07-2010, 03:03 PM
if you have the user id's that you want to send to you can simply edit your query to have
WHERE `id` IN(1,2,3,4,5)
where 1,2,3,4,5 are the user ids

partisanentity
01-07-2010, 04:04 PM
Thanks to the both of you, this is the problem I am having though:

My form has the following:

<select name="nform_newslrecipients[]">
<option>$row['username']</option>
</select>

So I end up with an Array of usernames in $_GET['recipients']

So I need a step to get each username, obtain the email for it and add it to $to.

Or is there an easier method? I have the feeling I am complicating things?

angst
01-07-2010, 04:17 PM
there are a few ways to do this,
personally, I'd prefer to set the option value to a user id then in the mail script run a select to get the username and email.

alternatively, you could do just a delimiter in the value like:



<option value='Bob|Bob@domain.com'>Bob</option>


then just explode the value in your loop.

Rowsdower!
01-07-2010, 04:24 PM
Thanks to the both of you, this is the problem I am having though:

My form has the following:

<select name="nform_newslrecipients[]">
<option>$row['username']</option>
</select>

So I end up with an Array of usernames in $_GET['recipients']

So I need a step to get each username, obtain the email for it and add it to $to.

Or is there an easier method? I have the feeling I am complicating things?

I think you might mean to say that you have an array of results in $recipients = $_POST['nform_newslrecipients'];

Is the form code you entered the actual code from the page or just a rough estimation? If it's not copy/pasted from your actual page please update it to be the actual code.

Under normal circumstances select boxes will return only one value (the one the user chose), not every value in the select box. If you are getting an array of results then something is not being done as it should. If your code truly does read as above then I believe your only issue is that the name used for the select element has brackets "[]" behind it. I have never played around with that method, but my understanding is that this indicates to the browser that this element will return multiple values (so the browser returns multiple values).

Try removing those brackets and see if you get only one entry for the select element.

JAY6390
01-07-2010, 04:28 PM
pretty sure it's to have an array of elements. Do you have multiple dropdowns of usernames and you select them with those? Checkboxes would definitely be a better choice IMO

angst
01-07-2010, 04:29 PM
Try removing those brackets and see if you get only one entry for the select element.

I think that maybe you've missed the point, he wants the array ( though yes, you can only get one value from a normal select, but he's likely use a multi ), he just needs a way to get both the persons name in email in one shot.

JAY6390
01-07-2010, 04:29 PM
Also, like it's been said above you need to have a value for your selects...

Rowsdower!
01-07-2010, 04:35 PM
I think that maybe you've missed the point, he wants the array ( though yes, you can only get one value from a normal select, but he's likely use a multi ), he just needs a way to get both the persons name in email in one shot.

Which is some of the source of my confusion. That's why I'm asking for a solid copy/paste from the code. Otherwise, using the brackets without using a multi select will (I believe) return all results in the select. I might be totally wrong about that.

Then again, as I said, I've never really toyed with this specific issue so I'm half guessing at a lot of it which probably isn't the most productive thing in the world to do.


Also, like it's been said above you need to have a value for your selects...

For the <option> tags, actually but yes, values certainly do need to be inserted here.

angst
01-07-2010, 04:37 PM
yes, i agree, current code would be nice.

also, without the multi, only one value would still be returned. but who knows, maybe he has a few of these single selects on one page. I *believe* that would still return the same result as a multi.

partisanentity
01-07-2010, 04:45 PM
Hey guys, sorry for the causing the confusion.

Some background info:

I wrote a simple newsletter/emailing feature. In the form the user can choose to send to:

ALL
or
select recipients

the form pulls all usernames from the db who have chosen to receive a newsletter and displays them in a <select multiple="multiple"> box.

Here is the complete code for the form (i have since added the email as a value for the <option>'s:


<h2>Write Newsletter</h2>
<?php

if ($_SESSION['username'] == "admin" && $_SESSION['logged_in'] == 1) {

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

if ($_SESSION['newsl_error'] == 1) {
echo 'You cannot select <b>ALL</b> and <b>specific</b> users, select either one or the other<br /><br />';
unset($_SESSION['newsl_error']);
}

if (isset($_SESSION['newsl_title']) && strlen($_SESSION['newsl_text']) > 5) {
$title = 'value="'.$_SESSION['newsl_title'].'"';
$text = $_SESSION['newsl_text'];
unset($_SESSION['newsl_title']);
unset($_SESSION['newsl_text']);
}

//get all usernames who agreed to receive a newsletter
$content = mysql_query("SELECT * FROM users WHERE id>1 AND newsletter=1");

echo '<form action="newsletterfunc.php" method="post" >';
echo '<table>';
echo ' <tr><td>Title: </td><td><input type="text" name="nform_newsltitle"'.$title.'></td><td rowspan="3">';
echo 'Select recipients';
echo '<select name="nform_newslrecipients[]" style="width: 100%;" size="30" multiple="multiple">';
echo '<option>ALL</option>';
while($row = mysql_fetch_array($content))
{
echo '<option value="'.$row['email'].'">'.$row['username'].'</option>';
}
echo '</select>';
echo '</td></tr>';
echo '<tr><td>Text: </td><td><textarea name="nform_newsltext" cols=80 rows=30>'.$text.'</textarea></td><td></td></tr>';
echo '<tr><td></td><td><input type="submit" value="send"></td><td></td></tr>';
echo '</table>';
echo '</form>';

} else {
echo '<h2>Access denied</h2>';
}
?>

Here is the complete php code:



<?php
//get the variables
$subject = $_POST['nform_newsltitle'];
$message = $_POST['nform_newsltext'];
$recipients = $_POST['nform_newslrecipients'];
$email = "contact@alhaffar.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'] . ',';
rtrim($to, ',');
}

} else {

//missing bit for sending mail to the select users only

}

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


?>


p.s. I only recently started learning to code in PHP so I bet this is painfully primitve and brutal to your eyes :) sorry

angst
01-07-2010, 04:49 PM
p.s. I only recently started learning to code in PHP so I bet this is painfully primitve and brutal to your eyes sorry

it's actually not too bad, I've seen much worse, atleat you've got the code some what formatted that helps allot while trying to read whats going on.


also, I answered your last question above:



there are a few ways to do this,
personally, I'd prefer to set the option value to a user id then in the mail script run a select to get the username and email.

alternatively, you could do just a delimiter in the value like:



<option value='Bob|Bob@domain.com'>Bob</option>


then just explode the value in your loop.

partisanentity
01-07-2010, 05:21 PM
I am thinking of doing the following:

Since I changed the value="" of each option to be the email address of the recipient, I could do this:


for ($i = 0; $i < count($recipients); $i++) {
$to .=$recipients[$i].', ';
echo rtrim($to, ",");

}

With this for loop I am getting the first entry twice though for some reason:

user@example.com, user@example.com, user2@other.com

partisanentity
01-07-2010, 05:51 PM
oh duh, it's in the for loop *facepalm*

Tulungo
01-19-2010, 05:52 PM
Hello all,

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


//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!



Ok i got a problem, i need to select a name to include in the message
the code looks like this:


$data =date("m", time());
$data1=date("d",time());

mysql_select_db( $db, $link ) or die ( "Couldn't open $db: ".mysql_error() );
$result = mysql_query( "SELECT Nome, Email FROM funcionarios where extract(day from Data_de_Nascimento)='$data1' and extract(month from Data_de_Nascimento)='$data' order by Data_de_Nascimento" );
$num_rows = mysql_num_rows( $result );

while ( $row = mysql_fetch_array( $result ) )
{

$to .= $row[Email] . ',';
rtrim($to, ',');
$na .= $row[Nome] . ','; //Name
rtrim($na, ',');


}

$sub="Feliz aniversario";
ini_set('SMTP', 'mail.clix.pt');
$subject = "$sub";
$message = "Sr. $na a fastforward ................................ Feliz aniversario";
$headers = 'From: bitlo@clix.pt' . "\r\n" .
'Reply-To: bitlo@clix.pt' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);


But in the message it apears all the names, and i need to associte a name to a email.....
Can please some one HELP ME!!!!!

tomws
01-19-2010, 10:01 PM
Why would you respond to an existing post (2 weeks old!) with a completely different problem? Start a new thread.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum