Jump to content

Email not being received via php mail


nicksahota

Recommended Posts

I have two separate sites hosted on 000webhost - I already have a php form which acts as a contact form on one website, users can fill it in and I will receive all mail to a designated mailbox - this works fine with the below code:

 

contact.php

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['message'])) {

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $phone = $_POST['phone'];
    $human = intval($_POST['human']);


    $to = 'justjalebi@hotmail.com'; 
    $from = 'JustJalebi Contact Form'; 
    $subject = 'JustJalebi - New Message From '.$name;

    $body ="From: $name\nE-Mail: $email\nPhone number: $phone\nMessage:\n\n$message";

    // Check if name has been entered
    if (empty($name)) {
        $errName = 'Please enter your name';
    } elseif(!preg_match("/^[a-z A-Z'-]+$/",$name)) { 
        $errNameInval = "Invalid name";
    } 


    // Check if email has been entered and is valid
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL) || !preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/", $email)) {
        $errEmail = 'Please enter a valid email address';
    }

    // Check if UK phone has been entered and is valid
    if (empty($phone) || !preg_match("/^(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/", $phone)) {
        $errPhone = 'Please enter a valid UK phone number';
    }

    //Check if message has been entered
    if (empty($message)) {
        $errMessage = 'Please enter your message';
    }
    // //Check if simple anti-bot test is correct
    if ($human !== 5) {
        $errHuman = 'Your anti-spam is incorrect';
    }
    else {
    // If there are no errors, send the email
        if (!$errName && !$errEmail && !$errPhone && !$errMessage && !$errNameInval) {
            if (@mail ($to, $subject, $body, $from)) {
                $result='<div class="alert alert-success" style="margin-bottom: 0px;">Thank You! A member of the JustJalebi team will be in touch.</div>';

                // header("refresh:4; url=http://www.justjalebi.co.uk/bootindex.html" ); 
                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                header("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
                header("Cache-Control: post-check=0, pre-check=0", false);
                header("Pragma: no-cache"); // HTTP/1.0
                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

            } else {
                $result='<div class="alert alert-danger" style="margin-bottom: 0px;">Sorry there was an error sending your message. Please try again later.</div>';
            }
        }
    }
}

On my other site I am trying to use the same logic where possible however the slight difference being that this form is a reset password form - the user will enter their email address, checks performed to see if it exists and then a randomly generated password will be sent to their email address (not my email address, another slight difference) followed by an update to the database with the newly generated password. When testing the below code it presents me with "Sorry there was an error sending your message. Please try again later" which is in the final if statement of the code.

This to me indicates that all works up until using the mail function, I am unsure whether the way in which I have added variables within the $to and $body variables is causing the issue?

 

forgot.php

<?php include('config.php');
    include('passwordGen.php');

    $errRemail = "";
    $errNoEmail = "";
    $password = randomPassword(8,1,"lower_case,upper_case,numbers");
    $result = "";

        if (isset($_POST['submit'])) {

                $email = $_POST['email'];   


                // Check if email has been entered and is valid
                if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL) || !preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/", $email)) {
                    $errRemail = '<div class="alert alert-danger alert-dismissable fade in" role="alert"  style="margin-bottom: 0px;">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close" style="font-family:sans-serif;">×</a>Please enter a valid email address</div>';
                }

                $stmt = $conn->prepare("SELECT username FROM blog_members WHERE email= ?");
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $result = $stmt->get_result();
                $row = $result->fetch_assoc();


                $to = $email;
                $from = '<admin@nicksahota.co.uk>'; 
                $subject = 'Account Details Recovery';                          
                $body = 'Hi'.$row['username'].',<br>You have requested your account details. Here is your account information 
                please keep this email safe as you may need it at a later stage.<br>Username: '.$row['username'].'
                <br>NEW Password: '.$password.'<br>Please login and change your password to something more memorable.<br>Regards Site Admin';
                $headers .= "MIME-Version: 1.0\n\n";
                $headers .= "Content-type: text/html\n\n";
                $headers .= 'From: admin@nicksahota.co.uk' . "\n\n" .
                'Reply-To: noreply@nicksahota.co.uk' . "\n\n" .
                'X-Mailer: PHP/' . phpversion();

                if($row == 0) {

                    $errNoEmail = '<div class="alert alert-danger alert-dismissable fade in" role="alert" style="margin-bottom: 0px;">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close" style="font-family:sans-serif;">×</a>Sorry, we cannot find your account details please try another email address.</div>';
                }
                else {
                    if (!$errRemail && !$errNoEmail) {      
                            if (@mail ($to, $from, $subject, $body, $headers))
                            {   
                                $stmt = $conn->prepare("UPDATE blog_members SET password = PASSWORD(?) WHERE email = ?");
                                $stmt->bind_param("ss", $password, $email);
                                $stmt->execute();
                                $stmt->close();

                                $result = '<div class="alert alert-success" style="margin-bottom: 0px;">An email has been sent to you containing your new login data.</div>';

                                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                                header("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
                                header("Cache-Control: post-check=0, pre-check=0", false);
                                header("Pragma: no-cache"); // HTTP/1.0
                                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

                            } else { 
                                $result='<div class="alert alert-danger alert-dismissable fade in" role="alert" style="margin-bottom: 0px;">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close" style="font-family:sans-serif;">×</a>Sorry there was an error sending your message. Please try again later.</div>';
                            }

                     }
                }               

            $conn->close(); 
        }   

    ?>

<form class="form-horizontal" role="form" method="post" id="reset" action="iforgot.php#reset">
   <div class="form-group">
      <div class="input-group">
         <span class="input-group-addon"><i class="fa fa-envelope fa-1x"></i></span>
         <input id="email" name="email" placeholder="email address" class="form-control"  type="text">
      </div>
   </div>
   <div class="form-group">
      <input id="submit" name="submit" class="btn btn-lg btn-primary btn-block" value="Reset Password" type="submit">
      <?php echo "<p class='text-danger'>$errRemail $errNoEmail</p>" ;?>
      <?php echo $result;  ?>
   </div>
</form> 

The fact that my contact form works indicates to me that this isn't an issue with the host provider, any help would be much appreciated. I've been pulling my hair out over this for days now :(

Apologies for the length of this post, its my 1st time here and I'm really hoping you guys can help me.

 

Regards,

NickSahota

Link to comment
Share on other sites

You don't see any difference between these two?

 

if (@mail ($to, $subject, $body, $from)) {
and

if (@mail ($to, $from, $subject, $body, $headers))

Also...

 

Take off the @, since that hides error messages you probably need to react to when developing.

 

You have security vulnerabilities that would allow someone to hijack this form and send out spam messages.

 

Note:

additional_headers does not have mail header injection protection. Therefore, users must make sure specified headers are safe and contains headers only. i.e. Never start mail body by putting multiple newlines.

Edited by Sepodati
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.