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'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With