Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send e-mail to multiple recipients from database query (PHP)

Tags:

php

email

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);
 }
like image 327
BigMike Avatar asked Feb 26 '23 16:02

BigMike


2 Answers

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); 
            }
        }
 } 
like image 52
PHPology Avatar answered Mar 05 '23 19:03

PHPology


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'];
}
like image 32
Borealid Avatar answered Mar 05 '23 17:03

Borealid