如何从数据库查询 (PHP) 向多个收件人发送电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3226138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send e-mail to multiple recipients from database query (PHP)
提问by BigMike
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);
}
回答by PHPology
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 :-|
尝试这样的操作,但有一点需要注意的是,您应该单独发送电子邮件,而不是将所有电子邮件地址分组在一个“收件人”字段中。其他用户可能不喜欢其他人看到这一点。也许您的 smtp 函数分解了数组,不确定 :-|
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);
}
}
}
回答by Borealid
mysql_fetch_arrayfetches an array with entries corresponding to each of the columns of a singlerow of your table. In other words, here it's an array containing one user's cEmailcolumn.
mysql_fetch_array获取一个数组,其条目对应于表的单行的每一列。换句话说,这是一个包含一个用户cEmail列的数组。
You need to fetch all the values into a singlearray before calling the mail functions. You could do it like this:
你需要获取所有值到一个单一的调用邮件功能前阵。你可以这样做:
$dest = array();
while ($arr = mysql_fetch_array($elist)) {
$dest[] = $arr['cEmail'];
}
回答by user3715138
I had a similar issue while trying to loop though my recipients' database table with the aim of sending personalized PEAR emails to each recipient.
我在尝试循环我的收件人的数据库表以向每个收件人发送个性化 PEAR 电子邮件时遇到了类似的问题。
The problem I encountered was that the loop would cease after one iteration until I amended $recipientsto just send the first item in the array, as illustrated in this code snippet. ($recipientsis an array of IDs for recipients):
我遇到的问题是循环将在一次迭代后停止,直到我修改$recipients为仅发送数组中的第一项,如此代码片段所示。($recipients是收件人的一组 ID):
/*PEAR mail set-up code included here*/
for ($i = 0; $i < count($recipients); $i++) {
$sql_recipients = "SELECT * FROM $data_table WHERE id = $recipients[$i] ORDER BY id ASC ";
$res_recipients = mysqli_query($mysqli,$sql_recipients)
or die (mysqli_error($mysqli));
$recipients_info = mysqli_fetch_array($res_recipients);
$recip_id = $recipients_info['id'];
$recip_organisation = $recipients_info['organisation'];
$recip_fname = $recipients_info['fname'];
$recip_lname = $recipients_info['lname'];
$recip_email = $recipients_info['email'];
/*PEAR mail code here */
$recipients[0] = $recip_email;
$mail->send($recipients[0], $hdrs, $body);
}
回答by Tarik
I learned to this from one of the examples in the book I am learning PHP from, Head First PHP & MySQL.
我从我正在学习 PHP 的书中的一个例子中学到了这一点,Head First PHP & MySQL。
What you can do is send each e-mail individually, but simultaneously, through a while loop. With a mysqli_queryselecting the e-mails, make a while loop that goes through my
您可以做的是单独发送每封电子邮件,但同时通过一个 while 循环发送。使用mysqli_query选择电子邮件,创建一个通过我的 while 循环
while ($row_data = mysqli_fetch_array($your_query_in_a_variable)) {
// Then you will set your variables for the e-mail using the data
// from the array.
$from = '[email protected]';
$to = $row_data['email']; // The column where your e-mail was stored.
$subject = 'Open Me!';
$msg = 'Hello world!';
mail($to, $msg, $from);
}
I hope that is clear. You basically just call the rows you want in your query, then use mysqli_fetch_array, which goes through each row every time it is called (someone correct me, if wrong) and will exit when there are no more rows left that were called.
我希望这很清楚。您基本上只是在查询中调用所需的行,然后使用mysqli_fetch_array,每次调用时都会遍历每一行(如果错误,有人纠正我),并在没有更多行被调用时退出。
回答by Kelly Copley
My suggestion would be use the php mail() function and set the smtp server parameters in your php.ini file.
我的建议是使用 php mail() 函数并在 php.ini 文件中设置 smtp 服务器参数。
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.
然后您所要做的就是查询您的数据库,将第一条记录作为您的收件人地址,然后遍历结果集并将每个电子邮件地址放入一个数组中。然后只需使用 join 函数用逗号连接数组,并将其用作标题字符串的 BCC。
Here is what I would use if possible. I've included a couple notes as //comments
如果可能的话,这是我会使用的。我已经包含了一些注释作为 //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.
希望这是有用的信息.. 随意将其拆开并使用您可能需要的任何内容,例如您是否可以使用 part 来实现您的 Mail 类。
回答by Benjamin Cremer
You schould notuse the php mail()function. It is dead slow because it does a full connect to the smtp server every single mail you send.
A good Mail library such as Zend_Mail connects only once and delivers the mails in one batch to the smtp server.
You should also notsend all your mails via a long BCC-Line. At least if you want your email not marked as spam (See thisQuestion and thisBlog-Entry by Jeff).
你不应该使用phpmail()函数。它非常慢,因为它会完全连接到您发送的每封邮件。
一个好的邮件库,例如 Zend_Mail,只连接一次,并将一批邮件发送到 smtp 服务器。
你也应该不通过长BCC行发送所有邮件。至少如果您希望您的电子邮件不被标记为垃圾邮件(请参阅此问题和Jeff 的此博客条目)。
<?php
function sendmail($cat, $user) {
// Setup mailer
require_once "Mail.php";
$smtp = Mail::factory('smtp', array(
'host' => "smtp.domain.com";
'auth' => true,
'username' => "USERNAME";
'password' => "PASSWORD";
));
// ALWAYS escape your variables!
$query = sprintf("SELECT cEmail FROM tblUsers WHERE cAlerts = 'All' AND cEAlerts = 'Yes' AND cPreferences LIKE '%s'",
mysql_real_escape_string($cat),
// submit the query
$result = mysql_query($query);
// iterate over each row
while ($row = mysql_fetch_assoc($result)) {
$from = "EMAIL ADDRESS";
$to = $row['cEmail'];
$subject = "SUBJECT";
$body = "BODY";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
// Send mail with individual to-address via smtp
$mail = $smtp->send($to, $headers, $body);
}
}
回答by Rubyist
Use this code to resolve your problem.
使用此代码解决您的问题。
//Connect to database
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$sql = "SELECT email FROM members";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res) )
{
$area .= $row['email']. ", ";
}
// read the list of emails from the file.
$email_list = explode(',', $area);
// count how many emails there are.
$total_emails = count($email_list);
// go through the list and trim off the newline character.
for ($counter=0; $counter<$total_emails; $counter++)
{
$email_list[$counter] = trim($email_list[$counter]);
}
$to = $email_list;
echo $to;

