简体   繁体   中英

Can't send Email using 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.">\r\n"
            ."Reply-To: ".$this->email."\r\n"
        ."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.. :(

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("\n.", "\n..", $message);
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: Test Org. <webmaster@test.org>' . "\r\n" .
        'Reply-To: webmaster@test.org' . "\r\n" .
        '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" 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.

Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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