简体   繁体   中英

Send email to recipients in MySQL DB using PHP

I'm working on a website in which, when a person enters email in the box, it will save it to MySQL DB.

I want to make a page, when once visited, will send email to the recipents in the DB. My script is here:

$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();

So, I'm trying $to to get those multiple emails from DB and then sending them an email which I've typed. What should I do to do that? I know I've left $to = ""; blank.

try this one...

  $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";
}
$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);

This would work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM