如何从我的数据库发送电子邮件到地址?

时间:2015-03-27 12:32:00

标签: php mysql email

我有一个发送电子邮件的表单,这一切正常但现在我想将电子邮件发送到存储在mysql数据库中的地址,但我无法弄清楚如何执行此操作。无论我尝试在下面的邮件脚本中将'$ to'设置为从数据库中提取的变量,它都不起作用。 谁能说出我做错了什么?感谢。

/// Get get recipients email address from database using id
$id= $_GET["id"];
$result = mysqli_query($conx, "SELECT email from mytable where id='$id'");
while($row = mysqli_fetch_array($result)) {
$to = $row["email"];
}

    if ($_GET["submit"]) {  
        $name =  htmlspecialchars($_GET['name']);
        $email = htmlspecialchars($_GET['email']);
        $message = $_GET['message'];
        $subject = 'Hello There';
        $body = "E-Mail: $email\n Message: $message";
        if (mail($to, $subject, $body)) {

        $result='<div class="alert alert-success">Your email has been sent</div>';
             }else{
        $result='<div class="alert alert-danger">Sorry there was an error sending your message.</div>';
    }
}
?>

1 个答案:

答案 0 :(得分:1)

你应该这样试试:

  

要从SQL INJECTION保护此代码,请阅读this article

/// Get get recipients email address from database using id
$id= (int) $_GET["id"];
$result = mysqli_query($conx, "SELECT email from mytable where id='$id'");
$row = mysqli_fetch_array($result);
$to = $row["email"];


    if ($_GET["submit"]) {  
        $name =  htmlspecialchars($_GET['name']);
        $email = htmlspecialchars($_GET['email']);
        $message = $_GET['message'];
        $subject = 'Hello There';
        $body = "E-Mail: $email\n Message: $message";
        if (mail($to, $subject, $body)) {

        $result='<div class="alert alert-success">Your email has been sent</div>';
             }else{
        $result='<div class="alert alert-danger">Sorry there was an error sending your message.</div>';
    }
}
?>