简体   繁体   English

jQuery和PHP联系人表格以发送电子邮件

[英]Jquery and PHP contact form to send email

This page is loaded within another html page when I click ' Contact ' on the horizontal menu. 当我在水平菜单上单击“ Contact ”时,此页面将加载到另一个html页面中。

I had to remove the $(document).ready(function() to get it running at all. 我必须删除$(document).ready(function()才能使其完全运行。

Everything seems to be working except I am not actually receiving the emails. 除了我实际上没有收到电子邮件,一切似乎都正常。 Any ideas? 有任何想法吗?

Thank you! 谢谢!

Here is the contact.html : 这是contact.html

<script type="text/javascript">
    $("#submit_btn").click(function() { 
        //collect input field values
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_message    = $('textarea[name=message]').val();

        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
            //data to be sent to server
            post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};

            //Ajax post data to server
            $.post('contact_me.php', post_data, function(data){  

                //load success massage in #result div element, with slide effect.       
                $("#result").hide().html('<div class="success">'+data+'</div>').slideDown();

                //reset values in all input fields
                $('#contact_form input').val(''); 
                $('#contact_form textarea').val(''); 

            }).fail(function(err) {  //load any error data
                $("#result").hide().html('<div class="error">'+err.statusText+'</div>').slideDown();
            });
        }

    });

    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });
</script>

<fieldset id="contact_form">
<div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>

    <label for="email"><span>Email Address</span>
    <input type="text" name="email" id="email" placeholder="Enter Your Email" />
    </label>

    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>

    <label><span>&nbsp;</span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    </label>
</fieldset>

And here is the contact_me.php 这是contact_me.php

<?php
if($_POST)
{
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 

    $to_Email       = "@gmail.com"; //Replace with recipient email address
    $subject        = 'ContactUS'; //Subject line for emails

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
    {
        die();
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        header('HTTP/1.1 500 Name is too short or empty!');
        exit();
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        header('HTTP/1.1 500 Please enter a valid email!');
        exit();
    }
    if(strlen($user_Message)<5) //check emtpy message
    {
        header('HTTP/1.1 500 Too short message! Please enter something.');
        exit();
    }

    //proceed with PHP email.
    $headers = "From: $user_Email\n" .
    "Reply-To: $user_Email\n" .
    "MIME-Version: 1.0\n" .
    "Content-Type: text/html\n" .
    "X-Mailer: PHP/" . phpversion();

    @$sentMail = mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);

    if(!$sentMail)
    {
        header('HTTP/1.1 500 Couldnot send mail! Sorry..');
        exit();
    }else{
        echo 'Hi '.$user_Name .', Thank you for your email! ';
        echo 'Your email has already arrived in my Inbox, all I need to do is Check it.';
    }
}
?>

Solution: I am using dreamhost and was trying to send mail from a dreamhost server but using a "From: @gmail" account. 解决方案:我正在使用Dreamhost,并试图从Dreamhost服务器发送邮件,但使用的是“发件人:@gmail”帐户。 I had to create a dreamhost @mydomain email and send it from there. 我必须创建一个dreamhost @mydomain电子邮件,然后从那里发送。 I checked the email logs and saw this error: 550 5.7.1 Sender domain not allowed. 我检查了电子邮件日志,并看到此错误:550 5.7.1不允许发件人域。 Can be read about here: http://wiki.dreamhost.com/PHP_mail() 可以在这里阅读: http : //wiki.dreamhost.com/PHP_mail()

There could be a number of problems here. 这里可能存在许多问题。

Firstly, die() is a poor substitute for proper error handling - at the very least, return a HTTP 500 error like you are doing with some of the other error cases in your code. 首先, die()不能很好地替代正确的错误处理-至少像处理代码中的其他一些错误情况一样,返回HTTP 500错误。

Secondly, as RUJordan has stipulated, @ suppresses error messages. 其次,按照RUJordan的规定, @禁止显示错误消息。 You also may not have a mail server; 您可能还没有邮件服务器; you should (in a development environment only) use the error_reporting(E_ALL) function. 您应该(仅在开发环境中)使用error_reporting(E_ALL)函数。

Thirdly, your email headers should be separated by \\r\\n , not \\n as described in the PHP Documentation . 第三,您的电子邮件标头应以\\r\\n分隔,而不是PHP文档中描述的\\n Your last header should also have the \\r\\n . 您的最后一个标头也应带有\\r\\n

Fourthly, sending email from the user's email address (let's use "abc@example.com") via your server (let's use "yourdomain.com") is a common spam tactic and often results in emails being flagged as spam and/or automatically deleted (Gmail has done this to me). 第四,通过服务器从用户的电子邮件地址(让我们使用“ abc@example.com”)发送电子邮件(让我们使用“ yourdomain.com”)是一种常见的垃圾邮件策略,通常会导致电子邮件被标记为垃圾邮件和/或自动已删除(Gmail已对我这样做)。 Try sending it from "noreply@yourdomain.com" - your server is now sending email from its own domain, and is hence much more trustworthy. 尝试从“ noreply@yourdomain.com”发送邮件-您的服务器现在正在从其自己的域发送电子邮件,因此值得信赖。 Regardless, you should check your spam folder - but this step lessens the chance of Gmail deleting it before it even reaches your inbox or spam folder. 无论如何,您都应检查垃圾邮件文件夹-但是此步骤可减少Gmail甚至在到达收件箱或垃圾邮件文件夹之前将其删除的可能性。

Finally, mail servers sometimes experience load. 最后,邮件服务器有时会承受负载。 Emails may not be delivered immediately; 电子邮件可能不会立即发送; try waiting up to several hours (tumblr once had a delay this long). 尝试等待长达几个小时(tumblr曾经有这么长时间的延迟)。 In addition, if this is a managed hosting platform, check with the host that everything is as it should be. 另外,如果这是一个托管主机平台,请与主机确认一切都应保持正常。

Not receving email in PHP could be by many reasons. 不接收PHP中的电子邮件可能有多种原因。 Check if your mail server is working, if your php.ini having correct smtp.host setting. 检查您的邮件服务器是否正常工作,如果您的php.ini的smtp.host设置正确。 If you use an external email address to receive, (for example google email), your mail server should be able to send message to it. 如果您使用外部电子邮件地址来接收(例如Google电子邮件),则您的邮件服务器应该能够向其发送消息。 Gmail requires authentication and SMTPS for sending which requires extra setup your mail server. Gmail需要身份验证和SMTPS才能发送,这需要对邮件服务器进行额外设置。 Also, check your spam folder! 另外,检查您的垃圾邮件文件夹!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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