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

Parvez Noor
PLUS
Parvez Noor
Courses Plus Student 15,917 Points

Need help using PHPMailer

Hi guys,

I'm making a simple website. It doesn't have too much functionality. The header and footer are included using php.

There is only one page - the index page.

On the index page, I have a simple contact form at the bottom. I've tried to connect this to my gmail using SMTP, after following Alena's building a basic PHP website course.

Everything seems to be working, except, it's not! I can still send the form without entering anything in the fields. Also, the page doesn't redirect to index.php?status=thanks. When I refresh the page, it still has problems with double form submission, and, worst of all, I'm still not getting any emails!

This is the website: http://tuwo.000webhostapp.com/

I'm assuming the whole if($_SERVER["REQUEST_METHOD"] == "POST") conditional is not even working, Can anyone help me figure out why?

Here is my code (I've removed most irrelevant html code to just show the form and the phpmailer code):

 <?php 
        use PHPMailer\PHPMailer\PHPMailer;
        use PHPMailer\PHPMailer\Exception;
        require 'vendor/phpmailer/src/PHPMailer.php';
        require 'vendor/phpmailer/src/Exception.php';
        require 'vendor/phpmailer/src/SMTP.php';

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

            if ($name == "" || $email == "" || $message == "") {
                $error_message = "Please fill in the required fields: Name, Email, Message";
                }
                if (!isset($error_message) && $_POST["address"] != "") {
                $error_message =  "Bad form input";
            }
            if (!isset($error_message) && !PHPMailer::validateAddress($email)) {
                $error_message =  "Invalid Email Address";
            }
            if(!isset($error_message)) {
                $email_body = "";
                $email_body .= "Contact by " . $name . " about " . $subject . "\n";
                $email_body .= "Message: " . $message . "\n";
                $email_body .= "Reply to " . $name . ": " . $email;

                $mail = new PHPMailer;
                try {
                    $mail->SMTPDebug = 2;
                    $mail->isSMTP();
                    $mail->Host = 'smtp.gmail.com';
                    $mail->Port = 587;
                    $mail->SMTPSecure = 'tls';
                    $mail->SMTPAuth = true;
                    $mail->Username = "email";
                    $mail->Password = "password";
                    $mail->setFrom('email', $name);
                    $mail->addReplyTo($email, $name);
                    $mail->addAddress('email', 'Parv Noor');
                    $mail->Subject = $subject . " from " . $name;
                    $mail->Body = $email_body;
                    if 
                        ($mail->send()) {
                        header("location:index.php?status=thanks");
                        exit;
                        } 
                } catch (Exception $e) { 
                    $error_message = "Mailer Error: " . $mail->ErrorInfo;
                }
            }
        }
        include("inc/header.php");
        ?>

          <section class="contact-us">
                <h1 class="get-in-touch">Get In Touch</h1>
                <?php if(isset($_GET["status"]) && $_GET["status"] == "thanks") {
                    echo  "<p> Thanks for the email! I&rsquo;ll check out your suggestion shortly!</p>"; 
                  } else { ?>
                <form class="contact-us-form" method="post" action="index.php">
                    <input class="name" type="text" id="name" name="name" placeholder="Name" value="<?php 
                    if (isset($name)) echo $name; ?>"/>
                    <input class="email" type="text" id="email" name="email" placeholder="Email" value="<?php 
                    if (isset($email)) echo $email;?>"/>
                    <input class="subject" type="text" id="subject" name="subject" placeholder="Subject" value="<?php 
                    if (isset($subject)) echo $subject;?>"/>
                    <textarea class="message" id="message" name="message" placeholder="Message"><?php 
                        if (isset($message)) echo htmlspecialchars($_POST['message']);
                        ?></textarea>
                    <input style="display:none" type="text" id="address" name="address" placeholder="Please leave blank" />
                    <input class="submit button" type="submit" value="Send">
                </form>
            </section>
            <?php } 
            include("inc/footer.php");
            ?>

1 Answer

A few things. First:

if ($name == "" || $email == "" || $message == "") {
                $error_message = "Please fill in the required fields: Name, Email, Message";
                }

This is not necessary. You can simply type required into your input elements and then the form won't submit until there is a value in those fields. Example:

<input type="text" name="example" id="exampleInput" required>

Here is why your redirect isn't happening:

if ($mail->send()) {
      header("location:index.php?status=thanks");
      exit;
}

The redirect will only happen if your mail sends. Because the redirect is not happening, your mail is not sending. If like me you use a XAMPP server for local development this might be because of security certificate issues, but it could be for any number of reasons having to do with the configuration of your local server. I suggest you output the error messages to the screen so you can see them and get a hint. Even if you don't understand the error messages, you can Google them and start doing some detective work and eventually, you will figure it out. I know because I've been in the same boat. Try using this code to see the error messages:

try {
           $mail->SMTPDebug = 2;
           $mail->isSMTP();
           $mail->Host = 'smtp.gmail.com';
           $mail->Port = 587;
           $mail->SMTPSecure = 'tls';
           $mail->SMTPAuth = true;
           $mail->Username = "email";
           $mail->Password = "password";
           $mail->setFrom('email', $name);
           $mail->addReplyTo($email, $name);
           $mail->addAddress('email', 'Parv Noor');
           $mail->Subject = $subject . " from " . $name;
           $mail->Body = $email_body;
           $mail->send()) 
       } catch (Exception $e) {
           echo "<br />" . $mail->ErrorInfo;
       }

Getting rid of the redirect for now and echoing out the error info will cause a wealth of information on what's going on when that script runs and it will give you enough clues that with some Googling you'll start figuring it out. Good luck!