Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Mailer send error when completing the form correctly

Hi,

I've been following the videos and all was going really well until after the "prioritizing error messages" section.

If I submit my form with mistakes, it all does what it should i.e. error messages are correct and nothing gets sent. However, when I fill in all the details correctly and submit, I get an error saying that the mail failed to send mailer error and yet the actual email does send and I receive it ok.

I have poured over my code trying to fix it myself but I'm at a loss. My code looks identical to the way Alena coded in the videos.

All I'm looking for is guidance from someone, to know if there is an obvious thing I'm missing like syntax etc.

I am sending the emails through xampp, which outputs the email to a dumped text file. It's been working fine at other stages of the development and still sends now, I just get the error message too.

My code is as follows (apologies, I've tried numerous ways to get the code to post correctly but I can't):

if ($_SERVER["REQUEST_METHOD"] == "POST"){
$name = trim(filter_input(INPUT_POST,"name",FILTER_SANITIZE_STRING));
$telephone = trim(filter_input(INPUT_POST,"telephone",FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST,"email",FILTER_SANITIZE_EMAIL));
$cardetails = trim(filter_input(INPUT_POST,"cardetails",FILTER_SANITIZE_STRING));
$claim = trim(filter_input(INPUT_POST,"claim",FILTER_SANITIZE_STRING));
$reg = trim(filter_input(INPUT_POST,"reg",FILTER_SANITIZE_STRING));
$message = trim(filter_input(INPUT_POST,"message",FILTER_SANITIZE_SPECIAL_CHARS));

if ($name == "" || $telephone == "" || $email == "" || $cardetails == "" || $claim == "" || $reg == "" || $message == "") {
    $error_message = "Sorry, you need to fill in all the madatory fields";
}
if (!isset($error_message) && $_POST["mileage"] != "") {
    $error_message = "Sorry, your evil spider bot is not welcome here! Mwah ha ha ha!";
}

require("includes/phpmailer/class.phpmailer.php");

$mail = new PHPMailer;
if (!isset($error_message) && !$mail->ValidateAddress($email)) {
    $error_message = "Invalid Email Address";
}

if(!isset($error_message)) {
    $email_body = "";
    $email_body .= "Name: " . $name . "\n";
    $email_body .= "Telephone: " . $telephone . "\n";
    $email_body .= "Email: " . $email . "\n";
    $email_body .= "Car Details: " . $cardetails . "\n";
    $email_body .= "Claim: " . $claim . "\n";
    $email_body .= "Registration: " . $reg . "\n";
    $email_body .= "Message: " . $message . "\n";

    $mail->setFrom($email, $name);
    $mail->addAddress('andy.hughes73@sky.com', 'Andy Hughes');     // Add a recipient
    $mail->isHTML(false); // Set email format to HTML

    $mail->Subject = 'Bodywork enquiry from ' . $name;
    $mail->Body    = $email_body;

    if(!$mail->send()) {
        header("location:contact-us.php?status=thanks");
        exit;
    }
    $error_message = 'Message could not be sent.';
    $error_message .= 'Mailer Error: ' . $mail->ErrorInfo;
}

}

Not sure if it's worth seeing the html form that goes with the script so I've included it just in case.

<article>
<?php if (isset($_GET["status"]) && $_GET["status"] == "thanks") {
    echo "<div class='thanks text-center'>
           <h2 class='uppercase'>Thank you</h2>
           <p>Thanks for your enquiry. We have received your message and will contact you shortly to discuss your requirements in more detail.</p>
           <p>Have a great day!</p>
           </div>";
    } else { ?>
<div class="intro text-center">
    <h2 class="uppercase">Give us a call or just pop in!</h2>
    <p>Please use the form below to get in touch with us. If you are making an enquiry about a car body repair, try to give us as much detail as you can. It will help us to get a better idea of the extent of any damage. You can also upload a photo showing the area where the work is required.</p>

  <p>If you would prefer to pop in, that's fine too. All we would ask is that you give us a call to check we're not in the middle of spraying cars when you arrive.</p>
</div>
    <div class="contact-form">
        <?php
        if(isset($error_message)) {
            echo "<p class='message'>". $error_message . "</p>";
        } else {
            echo "<div class='form-title'>
            <h1>Tell us what you need doing :)</h1>
            <h4>Describe your need and we'll get back to you asap!</h4>
            </div>";    
            }
            ?>
<form role="form" method="post" action="contact-us.php">
    <input class="text-input" id="name" type="text" name="name" placeholder="Your Name (required)" value="<?php if(isset($name)) { echo $name; } ?>">
    <input class="text-input" id="telephone" type="text" name="telephone" placeholder="Phone Number (required)" value="<?php if(isset($telephone)) { echo $telephone; } ?>">
    <input class="text-input" id="email" type="text" name="email" placeholder="Your Email" value="<?php if(isset($email)) { echo $email; } ?>">
    <input class="text-input" id="cardetails" type="text" name="cardetails" placeholder="Make/Model of Car (required)" value="<?php if(isset($cardetails)) { echo $cardetails; } ?>">
    <input class="text-input" id="claim" type="text" name="claim" placeholder="Insuance Claim or Private (required)" value="<?php if(isset($claim)) { echo $claim; } ?>">
    <input style="display: none" class="text-input" id="mileage" type="text" name="mileage" placeholder="Leave this field blank.">
    <input class="text-input" id="reg" type="text" name="reg" placeholder="Vehicle Registration" value="<?php if(isset($reg)) { echo $reg; } ?>">
    <textarea id="message" name="message" placeholder="Please describe your requirements in as much detail as possible. This will help us to better understand the extent of any repairs.  (required)">
<?php
    if(isset($message)) { 
        echo htmlspecialchars($message); 
    } 
    ?>
    </textarea>
        <button name="submit" type="submit" id="submit">Once you're done, push the button!</button> 
</form>
<?php } ?>
</div>
</article>

Hey Andy Hughes , You need to define $error_message with the default blank value.

 $error_message = " ";

//suppose if there is no empty variable in post data than you didn't have any $error_message which avoid next if condition
if ($name == "" || $telephone == "" || $email == "" || $cardetails == "" || $claim == "" || $reg == "" || $message == "") {
    $error_message = "Sorry, you need to fill in all the madatory fields";
}
if (!isset($error_message) && $_POST["mileage"] != "") {
    $error_message = "Sorry, your evil spider bot is not welcome here! Mwah ha ha ha!";
}

I can help you this much only but if you still getting an error so please paste the link of your workspace fork or In case uf you are working locally in your system send project files to me at singhashu163@gmail.com.

4 Answers

Ashish, thanks for your reply. I defined $error_message as an empty variable and tried that but it has made no difference. I think it seems like something to do with either the order of my code which is causing it to return an error status or it might be something to do with incorrect coding but i've searched over and over for any error.

Still stuck.

will you please send me your project files so I can explore code myself by working on it.

Ok so I managed to sort the major part of my issue by changing the "if" statement from (!$mail) to ($mail) and adding an "else" statement after processing the mail "email_body" element.

So the code for that bit now looks as follows:

if($mail->send()) {
    header("location:contact-us.php?status=thanks");
    exit;
} else {
if (isset($error_message)) {
        echo 'Message could not be sent.';
        echo $error_message .= 'Mailer Error: ' . $mail->ErrorInfo;
}

That seems to make almost everything work fine. The message now shows the correct errors and doesn't send the message and when the form is completed correctly, it sends the message and returns the "thank you" message.

The only issue I have now is trying to escape the output from the <textarea> content. At the moment, if I type something into the textarea, with the code below:

<textarea id="message" name="message" placeholder="Please describe your requirements in as much detail as possible. This will help us to better understand the extent of any repairs. (required)">
<?php
    if(isset($message)) {
        echo htmlspecialchars($message, ENT_QUOTES);
    }
    ?>

such as, "I need a new wing for my car". I get the following type of output in the email:

Message: &#9;&#9;&#9;I need a new wing for my car&#9;&#9;&#9;&#9;&#9;&#9;&#9;

I'm thinking it might have something to do with the "placeholder" content in the textarea. Any thoughts? I will do a bit more testing and hope to find the solution.

Thanks

After a little bit of testing I can now say with reasonable confidence that the textarea issues doesn't seem due to the placeholder text as it performs exactly the same with, or without the placeholder tag.

What seems odd is that when I refresh the form and go to enter text into the textarea, I can place my cursor anywhere along the first line and type. What I then get in the email appears to be the syntax for whitespace before and after my typed text. If I place my cursor at the start of the textarea and submit my form, the retained text in the field is now half way across the textarea box as though whitespace has been inserted. Sure enough, when I look at the email output, whitespace characters seem to have been added.

Can't think why this is happening or what else to try and sort it. Any help would be great thanks.

Ok all sorted! I was using the following code:

<textarea id="message" name="message" placeholder="Please describe your requirements in as much detail as possible. This will help us to better understand the extent of any repairs. (required)">
<?php
    if(isset($message)) {
        echo htmlspecialchars($message, ENT_QUOTES);
    }
?>
</textarea>

Without knowing any better, I was unaware that by indenting my code in my html editor it was actually physically adding whitespace to the "textarea" field. I removed all of the indents and hey presto, problem sorted.