为什么我无法向从数据库中获取的电子邮件地址发送电子邮件?

时间:2016-04-16 10:33:03

标签: php forms email mysqli

我的网站允许用户向给定的电子邮件地址发送电子邮件,该电子邮件地址保存在我的数据库中。现在我的网站已经上线了,我正在测试这样的东西,事实证明我的contact.php无效。当我尝试发送电子邮件时,我总是收到消息Sorry, there was an error sending your message.

My Contact.php具有以下代码

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'dbcontroller.php';
if (isset($_POST['sendMessage'])) {
    if(empty($_POST['firstname']) || empty($_POST['lastname']) || empty($_POST['email']) || empty($_POST['message'])) {
        echo "<script type='text/javascript'>alert('Please fill all the fields.');window.location.href='contact.php'</script>";
    }
    else{
        $sql = "SELECT * from contact";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_array($result);
        $to = $row['email'];
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $mailfrom = $_POST['email'];
        $message = $_POST['message'];
        $headers = "From:" . $firstname . " " . $lastname . "\r\n" . $mailfrom;
    if (mail($to, $message, $headers)) {

     echo "<script type='text/javascript'>alert('Your email has been sent! Thank you for contacting us!');window.location.href='contact.php'</script>";
    }
    else{
        echo "<script type='text/javascript'>alert('Sorry there was an error sending your message.');window.location.href='contact.php'</script>";
        }
}
} 
?>

这是我的联系表单,与PHP代码在同一页面中。

<form method="post" action"">

    <label>First Name </label>
<input type="text" class="form-control" placeholder="Firstname" name="firstname" required="required" />

    <label>Last Name</label>
<input type="text" class="form-control" placeholder="Lastname" name="lastname" required="required"/>

    <label>Email-address</label>
<input type="email" class="form-control" placeholder="Email" name="email" required="required" maxlength="200"/>

    <label>Message </label>
<textarea name="message" class="form-control" required="required" rows="4" cols="50" maxlength="500"></textarea>

    <input type="submit" name="sendMessage" value="Send Email" class="btn btn-primary pull-right"/>
</form>

1 个答案:

答案 0 :(得分:0)

首先,我可以看到,$ fn和$ ln没有在任何地方填充,因此它们是空值。这可能是一个原因。 我看到的另一件事是标题。我认为他们缺少一些简单的东西。 以下是我一直使用的:

[snipp]

$headers = "From: $botmail\n"; // Who the email was sent from
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "X-Priority: $priority\n"; // The priority of the mail

$success = mail($receivermail, $subject, $message, $headers);