如何从HTML表单发送邮件?

时间:2018-04-02 04:18:44

标签: php html forms email

我做了一个表单,我的任务是发送邮件到邮件服务器。我尝试了mailto HTML属性。但是失败了。然后开始使用php.It也没有工作。所以我非常需要帮助。

<form method="post" action="form-to-email.html">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="exampleInputName">Your Name (required)</label>
                                        <input type="text" class="form-control"  name="name" placeholder="Enter Your Name">

                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">Your Email (required)</label>
                                        <input type="Email" class="form-control" name="email" placeholder="Enter Your Email">

                                    </div>
                                    <div class="form-group">
                                        <label for="exampleInputTextarea">Your Message</label>
                                        <textarea class="form-control" placeholder="Enter Your Message" rows="4" name="message"></textarea>
                                    </div>

                                    <button type="submit" value="Send Email" class="btn btn-default">Send</button>

                                    </div>
                                </form>

这是我的PHP代码。

<?php
if(isset($_POST['name'])&&isset($_POST['email'])){
$name = $_POST['name'];
  $visitor_email = $_POST['email'];
  $message = $_POST['message'];
    $email_from = 'dbgreen71@heidianderson.com.au';
    $email_subject = "New Form submission";
    $email_body = "You have received a new message from the user $name.\n".    
                            "Here is the message:\n $message".    
$to = "dbgreen71@heidianderson.com.au";
  $headers = "From: $email_from \r\n";
  $headers .= "Reply-To: $visitor_email \r\n";
  mail($to,$email_subject,$email_body,$headers);
}
?>

有人请帮助我。我真的找不到任何方法来完成这项任务。

1 个答案:

答案 0 :(得分:0)

试试这个并告诉你是否有任何错误:

<?php
    $visitor_email = $_POST['email'];
    $message = $_POST['message'];
    $email_subject = "New Form submission";
    $to = "dbgreen71@heidianderson.com.au";
    $subject = $email_subject;
    $email_from = 'dbgreen71@heidianderson.com.au';
    $header = "From:dbgreen71@heidianderson.com.au \r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-type: text/html\r\n";

    $retval = mail ($to,$subject,$message,$header);

    if( $retval == true ) {
    echo "Message sent successfully...";
    }else {
    echo "Message could not be sent...";
    $errorMessage = error_get_last()['message'];
    echo $errorMessage;
    }
?>

此外,我添加了错误处理代码,如果您收到与邮件相关的任何错误,将在不久的将来帮助您。 另一件事,如果您需要标题然后只使用它,否则它是没有用的。您甚至可以发送没有标题的电子邮件。