使用PHP向MySQL DB中的收件人发送电子邮件

时间:2015-01-20 07:01:06

标签: php mysql email mysqli

我正在开设一个网站,当一个人在框中输入电子邮件时,它会将其保存到MySQL数据库。

我想制作一个页面,一旦访问过,就会向数据库中的配方发送电子邮件。我的脚本在这里:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT email FROM subscribers";
$result = $conn->query($sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
       echo $row["email"]. "&nbsp";
    }
} else {
    echo "0 results";
}

$to = "";
$subject = "PrakashSoft Website has been Lauched!";
$txt = "Respected Mam/Sir,

    PrakashSoft Website has been lauched from 3rd May 2015! To visit the website use the following link:

    http://www.prakashsoft.esy.es/home.php";
$headers = "From: noreply@prakashsoft.esy.es";

mail($to, $subject, $txt, $headers);
$conn->close();

所以,我正在尝试$to从数据库中获取这些多封电子邮件,然后向他们发送我输入的电子邮件。我该怎么做呢?我知道我已将$to = "";留空了。

2 个答案:

答案 0 :(得分:0)

尝试这个...

  $sql = "SELECT GROUP_CONCAT(DISTINCT email)
    FROM subscribers";
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
      $to = $row["email"];
} else {
    echo "0 results";
}

答案 1 :(得分:0)

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}    

$sql = mysql_query("select email from subscribers");
    $recipients = array();
    while($row = mysql_fetch_array($sql)) {
        $recipients[] = $row['email'];
    }

    $to = implode(",", $recipients);
    $subject = "E-mail subject";
    $body = "E-mail body";
    $headers = "From: noreply@prakashsoft.esy.es" ;

    mail($to, $subject, $body, $headers);

这样可行