我正在尝试编写PHPMailer来发送电子邮件。我正在使用带有mysqli_fetch_array的while循环来从MySQL中提取电子邮件记录,并将“email”数据库字段分配给名为“$ to”的变量,并将其添加到PHPMailer $ mailer-> AddAddress(“user@domain.com”) )打电话。
该脚本有效但仅向数据库中找到的第一个收件人发送电子邮件。关于我搞砸的地方的任何线索? THX!
$from = 'myemail@gmail.com';
$from_name = 'My Name';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$dbc = mysqli_connect('localhost', 'username', 'the_password', 'database_name')
or die('Error connecting to mysql');
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){
$to = $row['email'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name,\n$text";
}
require("PHPMailer_v5.1 2/class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = TRUE;
$mailer->Username = 'myemail@gmail.com'; // Sender's gmail address
$mailer->Password = 'the_password'; // Sender's gmail password
$mailer->From = "$from"; // Sender's email address
$mailer->FromName = "$from_name"; // senders name
$mailer->Body = "$msg";
$mailer->Subject = "$subject";
$mailer->AddAddress("$to"); // Recipient
if(!$mailer->Send())
{
echo 'Email sent to:' . $to . '<br/ >';
echo "Mailer Error: " . $mailer->ErrorInfo;
}
else
{
echo 'Email sent to:' . $to . '<br/ >';
}
mysqli_close($dbc);
答案 0 :(得分:1)
您过早关闭while
循环。
将其更改为:
require("PHPMailer_v5.1 2/class.phpmailer.php");
while ($row = mysqli_fetch_array($result)){
$to = $row['email'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name,\n$text";
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = TRUE;
$mailer->Username = 'myemail@gmail.com'; // Sender's gmail address
$mailer->Password = 'the_password'; // Sender's gmail password
$mailer->From = "$from"; // Sender's email address
$mailer->FromName = "$from_name"; // senders name
$mailer->Body = "$msg";
$mailer->Subject = "$subject";
$mailer->AddAddress("$to"); // Recipient
if(!$mailer->Send())
{
echo 'Email sent to:' . $to . '<br/ >';
echo "Mailer Error: " . $mailer->ErrorInfo;
}
else
{
echo 'Email sent to:' . $to . '<br/ >';
}
// Then close your while loop here
}
mysqli_close($dbc);
答案 1 :(得分:0)
在循环结束时,$to
(和其他变量)将被设置为循环的最后一次迭代。
调整代码,以便在循环上方初始化PHPMailer,然后在循环中调用$mailer->AddAddress($to)
。
请勿忘记在循环结束后调用$mailer->Send()
:)
答案 2 :(得分:0)
我以这种方式做到了:
$to = $row['email'];
$mailer->AddAddress("{$to}"); // Recipient