从数据库查询发送多封电子邮件

时间:2014-02-01 03:18:01

标签: php mysql email

您好我想将电子邮件发送到我的数据库中的联系人列表。代码不选择数据库。我想知道我能做些什么来解决这个问题。这段代码似乎一直有效,直到找到mysql_query命令。它返回的唯一错误是数据库未被选中且失败。我回显了代码行,它没有传递$rs = mysql_query($query_Events, $gpd) or die(mysql_error());命令。 请帮助我理解我怎么能正确解决这个问题。

 <?php 


$hostname_gpd = "127.0.0.1";
$database_gpd = "localmail";
$username_gpd = "";
$password_gpd = "";
$gpd = mysqli_connect($hostname_gpd, $username_gpd, $password_gpd) or  trigger_error(mysqli_error(),E_USER_ERROR)
; 

$subject=$_POST['Subject'];
$note=$_POST['Message'];

$sender="xxxx@yahoo.com"; // Your Email here.

echo "Email has been sent to:";

// Connect database

mysqli_select_db($gpd,$database_gpd);

$query_Events = "SELECT `Email` FROM email_list ORDER BY `id` ASC";

$rs = mysqli_query($gpd,$query_Events) or die(mysqli_error($gpd));

if(!$rs)
{

echo mysqli_error();
}
else{       // Do while loop to send email.
while($row = mysqli_fetch_assoc($rs)){
$to=$row['Email'];
$mail_from="From:$Email n";
$mail_from .="Content-Type: text/html; charset=utf-8 n";

mail($to,$subject,$note,$mail_from);

// Show sent emails.
echo "$row[Email]<br>";
}}

?>

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。

您的mail() headers无效,遗失\r\n,其中您只有n且已重新格式化。

结论性测试电子邮件没有进入雅虎和Gmail的垃圾邮件,而是登陆收件箱。

我还添加了数据库参数;即使您使用mysqli_select_db()

声明它,也需要在那里

From:应该使用$sender变量,而不是$Email,因为每个收到电子邮件的人都会认为它来自“他们”,我怀疑这是什么你想做什么。

(已经过测试并为我工作)并假设mail()可用,请在您的服务器上正确设置并运行。

<?php
$hostname_gpd = "127.0.0.1";
$database_gpd = "localmail";
$username_gpd = "";
$password_gpd = "";
$gpd = mysqli_connect($hostname_gpd, $username_gpd, $password_gpd, $database_gpd) 
or  trigger_error(mysqli_error(),E_USER_ERROR);

$subject=$_POST['Subject'];
$note=$_POST['Message'];

/* my testing variables
$subject= "The subject";
$note= "My little note";
*/

$sender="xxxx@yahoo.com"; // Your Email here.
echo "Email has been sent to: ";

$query_Events = "SELECT `Email` FROM email_list ORDER BY `id` ASC";
$rs = mysqli_query($gpd,$query_Events) or die(mysqli_error($gpd));

if(!$rs)
{
echo mysqli_error();
}
else{ // Do while loop to send email.
    while($row = mysqli_fetch_assoc($rs)){
    $to=$row['email'];

$mail_from = "From: $sender" . "\r\n" . "Reply-To: $sender" . "\r\n";
$mail_from .= "Content-type: text/html; charset=utf-8 \r\n";

mail($to,$subject,$note,$mail_from);

// Show sent emails.
// echo "$row[email]<br>";
echo "$row[email]" . "<br>";
    }
}
?>

还要确保表单元素已命名并与PHP处理程序变量匹配。

例如:

<form action="handler.php" method="post">
Enter subject: <input type="text" name="Subject">
<br>
Enter message:
<br>
<textarea rows="5" name="Message" cols="50"></textarea>
<input type="submit" value="Submit" name="submit">
</form>

Lettercase对于POST变量非常重要,您目前使用的是混合大小写字母。

Subjetsubject不同,因为Messagemessage

不同