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

前端 未结 7 2450
南方客
南方客 2020-12-29 16:41

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

7条回答
  •  执笔经年
    2020-12-29 16:58

    My suggestion would be use the php mail() function and set the smtp server parameters in your php.ini file.

    Then all you have to do is query your db, pull the first record out as your to address and then loop through the result set and put each email address into an array. Then just use the join function to join the array with commas and use it as the BCC for the header string.

    Here is what I would use if possible. I've included a couple notes as //comments

    function sendmail($cat, $user) {
    
        $result = mysql_query("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%$cat%';");
    
        //pull out first email as the to address
        $to = mysql_fetch_array($result);
    
        //create array to store all the emails
        $elist = array();
    
        //loop through and put each email into an array
        // you might be able to skip this altogether if you can just join $result
        // but I'm to lazy to investigate what all is being returned 
        while($row = mysql_fetch_assoc($result)){
            $elist[] = $row['cEmail'];
        }
    
        //join the emails into a comma separated string
        $bcc = join($elist, ",");
    
        $from = "EMAIL ADDRESS";
        $subject = "SUBJECT";
        $body = "BODY";
    
        $headers  = "From: ". $from ."\r\n";
        $headers  .="BCC: ". $bcc ."\r\n";
    
        mail($to, $subject, $body, $headers);
    }
    

    Hopefully this is useful information.. Feel free to pick it apart and use whatever you may need, like if you can use part to implement your Mail class.

提交回复
热议问题