Contact-Us表单返回成功,但不发送电子邮件:PHP | HTML

时间:2017-01-18 07:56:16

标签: javascript php html contact-form

我正在建立的网站的联系我们形式几个月来困扰着我。没有错误,一切似乎都是成功的,除了我可以收到电子邮件的部分。仍然没有收到任何电子邮件,感谢任何有启发性的信息。

这是PHP代码。

<?php
// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
   echo "No arguments Provided!";
   return false;
}

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'example@gmail.com'; 
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact      form.\n\n"."Here are the details:\n\nName: $name\n\nEmail:            $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: examplesender@hotmail.com\n"; 
$headers .= "Reply-To: $email_address";   
if(mail($to,$email_subject,$email_body,$headers)){
 return true;   
 }
return false;         
?>

这是JS代码

$(function() {

$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function($form, event) {
        event.preventDefault(); // prevent default submit behaviour
        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var message = $("textarea#message").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }
        $.ajax({
            url: "././mail/contact_me.php",
            type: "POST",
            data: {
                name: name,
                email: email,
                message: message
            },
            cache: false,
            success: function() {
                // Success message
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Your message has been sent! </strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#contactForm').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            },
        });
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

$("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
});
});

$('#name').focus(function() {
$('#success').html('');
});

这是HTML代码。

<!-- Contact Section -->
<section id="contact">
    <div class="container">
        <div class="row">
            <div class="col-lg-12 text-center">
                <h2 class="section-heading">Talk to Us</h2>
                <h3 class="section-subheading text-muted"></h3>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">
                <form name="sentMessage" id="contactForm" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="text" name="name" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="email" name="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                               <!-- <input type="tel" class="form-control" placeholder="Your Country *" id="country" required data-validation-required-message="Please enter your country."> -->

                                <select  class="form-control" id="country">
                                    <option value="0" selected="selected">Your Country *</option>
                                    <option value="AF">Afghanistan</option>
                                    <option value="AX">Ã…land Islands</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <textarea class="form-control" name="message" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <div class="col-lg-12 text-center">
                            <div id="success"></div>
                            <button type="submit" class="btn hvr-pulse-grow">Send Message</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>

1 个答案:

答案 0 :(得分:0)

尝试使用PHPMailer Library https://github.com/PHPMailer/PHPMailer 步骤:1 创建一个文件夹'Mail' 步骤:2 将这些文件class.phpmailer.php,class.pop3.php,class.smtp.php,PHPMailerAutoload.php复制到从给定网址下载的文件夹中 步骤:3 创建自己的sendMail.php文件并将上面的代码粘贴到其中并更改require参数,如hostname,from,to,userid,password,smtp port number,

require 'PHPMailerAutoload.php';
function sendEmail($subject, $body, $to, $cc = "", $bcc = "") {
$mail = new PHPMailer ();

$mail->isSMTP(); // Set mailer to use SMTP
$mail->setFrom('from@mail.com', 'Title'); // Set who the message is to be sent from
$mail->Host = 'hostname | ip address'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->Port = 587; // Set the SMTP port number - 587 for authenticated TLS

$tos = explode(";", $to);
foreach ($tos as $key => $val) {
    $mail->addAddress($val); // Add a recipient
}
$ccs = explode(";", $cc);
foreach ($ccs as $key => $val) {
    $mail->addCC($val); // Add a recipient
}

$mail->addBCC($bcc);
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->isHTML(true); // Set email format to HTML

$mail->Subject = $subject;

$mail->msgHTML($body);
$mail->Body = $body;
if (!$mail->send()) {
    echo '-';//'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
    exit ();
} else {
    return true; //'Message has been sent';
}

}