weixin_33698043 2014-06-10 04:45 采纳率: 0%
浏览 28

无法使用PhP发送电子邮件

I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)

<?php
/*
* Contact Form Class
*/


header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$admin_email = 'sgg3590@rit.edu'; // Your Email
$message_min_length = 5; // Min Message Length


class Contact_Form{
    function __construct($details, $email_admin, $message_min_length){

        $this->name = stripslashes($details['name']);
        $this->email = trim($details['email']);
        $this->subject = 'Contact from Your Website'; // Subject 
        $this->message = stripslashes($details['message']);

        $this->email_admin = $email_admin;
        $this->message_min_length = $message_min_length;

        $this->response_status = 1;
        $this->response_html = '';
    }


    private function validateEmail(){
        $regex = '/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';

        if($this->email == '') { 
            return false;
        } else {
            $string = preg_replace($regex, '', $this->email);
        }

        return empty($string) ? true : false;
    }


    private function validateFields(){

        if(!$this->name)
        {
            $this->response_html .= '<p>Please enter your name</p>';
            $this->response_status = 0;
        }

        // Check email
        if(!$this->email)
        {
            $this->response_html .= '<p>Please enter an e-mail address</p>';
            $this->response_status = 0;
        }

        // Check valid email
        if($this->email && !$this->validateEmail())
        {
            $this->response_html .= '<p>Please enter a valid e-mail address</p>';
            $this->response_status = 0;
        }

        // Check message length
        if(!$this->message || strlen($this->message) < $this->message_min_length)
        {
            $this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
            $this->response_status = 0;
        }

    }


    private function sendEmail(){

        $mail = mail($this->email_admin, $this->subject, $this->message,
             "From: ".$this->name." <".$this->email.">
"
            ."Reply-To: ".$this->email."
"
        ."X-Mailer: PHP/" . phpversion());

        if($mail)
        {
            $this->response_status = 1;
            $this->response_html = '<p>Thank You!</p>';
        }
        else
        {
        $this->response_status = 0;
            $this->response_html = '<p>Sending failed</p>';
        }

    }


    function sendRequest(){

        $this->validateFields();

        if($this->response_status)
        {
            $this->sendEmail();
        }

        $response = array();
        $response['status'] = $this->response_status;   
        $response['html'] = $this->response_html;

        echo json_encode($response);
    }
}


$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();

?>

here is how I am calling it

BRUSHED.contactForm = function(){
    $("#contact-submit").on('click',function() {
        $contact_form = $('#contact-form');

        var fields = $contact_form.serialize();

        $.ajax({
            type: "POST",
            url: "_include/php/contact.php",
            data: fields,
            dataType: 'json',
            success: function(response) {

                if(response.status){
                    $('#contact-form input').val('');
                    $('#contact-form textarea').val('');
                }

                $('#response').empty().html(response.html);
            }
        });
        return false;
    });
}

And here is my form

<form id="contact-form" class="contact-form" action="#">
                                <p class="contact-name">
                                    <input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
                                </p>
                                <p class="contact-email">
                                    <input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
                                </p>
                                <p class="contact-message">
                                    <textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
                                </p>
                                <p class="contact-submit">
                                    <a id="contact-submit" class="submit" href="#">Send Your Email</a>
                                </p>

                                <div id="response">

                                </div>
                            </form>

The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail) I followed this code from a website and I Don't really understand whats wrong here.. :(

  • 写回答

2条回答 默认 最新

  • weixin_33713707 2014-06-10 06:39
    关注

    First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test@test.org but From: localhost.

    Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:

    <?php
    try {
        $to      = 'user@test.org';
        $subject = 'Mail Test';
        $message = <<<TEXT
    Mail request received
    TEXT;
        $message = str_replace("
    .", "
    ..", $message);
        $headers  = 'MIME-Version: 1.0' . "
    ";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "
    ";
        $headers .= 'From: Test Org. <webmaster@test.org>' . "
    " .
            'Reply-To: webmaster@test.org' . "
    " .
            'X-Mailer: PHP/' . phpversion();
    
        mail($to, $subject, $message, $headers);
        printf("Mail sent to " + $to);
    } catch (Exception $e) {
        printf("Error occured: " + $e);
    }
    ?>
    

    If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent@test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.

    评论

报告相同问题?

悬赏问题

  • ¥15 Qt安装后运行不了,这是我电脑的问题吗
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法