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

Taylor Plante
Taylor Plante
22,283 Points

Strange error with SMTP email configuration (PHP)

I built a simple website with HTML and CSS a while back and have since added a form and attempted to implement the PHP I've learned. Below is the code for the form and the PHP that comes after it (wasn't sure where to add the PHP). I'm getting a very strange error where some of my contact page's styles are being stripped and a great deal of content is thrown in from GitHub's PHPMailer download area!

<div class="contactwrap">
            <div class="contactphone">
                <p>Call me!</p>
                <img src="img/phone.png" rel="phone">
                <p id="number">(612) 876-****</p>
            </div>
            <div class="contactemail">
                <p id="contactp"><img src="img/email.png" rel="email"> ...or send an email:</p>
            </div>
            <div class="contactinfo">
                <form method = "post" action="contact.php">
                    <input class="info" type="text" name="name" id="name" placeholder="Name">
                    <input class="info" type="email" name="email" id="email" placeholder="Email">
            </div> 
            <div class="contactmessage">
                    <textarea id="message" name="message" placeholder="Message area..."></textarea>
            </div>
            <div class="contactsubmit">
                    <input id="submit" type="submit" name="submit" value="Send">
            </div>
                </form>
                <?php 
                    require_once('inc/phpmailer/PHPMailerAutoload.php');
                    require_once('inc/phpmailer/class.phpmailer.php');
                    $mail = new PHPMailer();

                    $mail->isSMTP();
                    $mail->SMTPDebug = 2;
                    $mail->Debugoutput = 'html';

                    $mail->Host = "smtp.postmarkapp.com";
                    $mail->Port = 25;
                    $mail->SMTPAuth = true;
                    $mail->Username = "brighton@santeedogsitter.com";
                    $mail->Password = "********not_the_real_pw*********";

                    $mail->setFrom('taylorplante99@gmail.com', 'Taylor Plante');
                    $mail->addReplyTo('brighton@santeedogsitter.com', 'Brighton Plante');
                    $mail->addAddress('taylorplante99@gmail.com', 'Taylor Plante');

                    $mail->Subject = 'PHPMailer SMTP test';

                    if (!$mail->send()) {
                        echo "Mailer Error: " . $mail->ErrorInfo;
                    } else {
                        echo "Message sent!";
                    }
                ?>
        </div> 

5 Answers

I would try following these steps:

  • Place all the php mailer code before any html. Get it in before you declare the doctype
  • When you request the same page (via your form) you will do so with a POST request. You only want to run the mailer code when you have a valid POST request, so wrap the whole code in an if statement:
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

// validate
// do loads of awesome form stuff
// if no error messages from validation, send mail
// show success version of page / redirect to same page with $_GET variable of success

// if validation fails, don't redirect

}


if ($_GET['status'] == 'success') {

  // show message sent success message

} else {

// show error messages
// show form
}

Just some ideas for a skeleton! But I would definitely restrict running the code when post and before html. If you're still getting the same error messages after, post again!

Taylor Plante
Taylor Plante
22,283 Points

Thanks for your reply! I'm going to give that a shot and get back to you.

Taylor Plante
Taylor Plante
22,283 Points

Okay, so I opened and closed all the PHP code above the doctype. Regarding your suggestions, I plan to add validation for fields and conditionals for error messages (among other things), but right now I'm looking for a bare bones solution to get the emails sending. With that said, I wrapped the PHP I had above with the first "if" statement you wrote at the top.

The result is that my page is no longer partially displaying GitHub, and all the styles are as I originally had them, but I can't get the email to send. Another interesting point: after I hit submit on the completed form I am redirected to GitHub's page! No weird hybrid pages, but still weird--seems I am getting closer?

Robert Bojor
Robert Bojor
Courses Plus Student 29,439 Points

Hi Taylor,

You will only need to require the auto loader from phpMailer, no need for the rest of the files...

require_once('inc/phpmailer/PHPMailerAutoload.php');

Also the form opens inside an opened div and closes outside that div, while this is not relevant to your problem, it is however a good practice to keep the form open and close tags on the same html level.

I see you are debugging the mail attempt to send, care to share that error log? Usually when phpMailer doesn't send the messages the answer is in the log it creates.

Sweet! Sounds like you're getting there :-p

You can read more about only including the Autoload file like Robert Bojor mentioned here.

You might also be able to see some errors by exiting the code after any errors are created. Mine is below. I would post my code but I haven't used SMTP so won't be much help! I will say that Treehouse have a blog post (I apologise if you're already seen.)

<?php

//if send is successful, change page location. .htaccess interprets contact-us/thanks --> contact-us.php?status=thanks
if($mail->Send()) {
    header("Location: " . BASE_URL . "contact-us/thanks");
    exit;
} else {
    //if unsuccessful create error message for displaying on page if exists.
    $error_message = "There was a problem sending the email: " . $mail->ErrorInfo;
    exit;
}

Another debugging method you could try is to see when the redirect happens by exiting the code prior to attempting to send and you could test certain variables. You could also dump out the object to see if anything is wrong.

Taylor Plante
Taylor Plante
22,283 Points

Alright I'm back... I tried to make the suggested edits, including removing unnecessary includes and running some debugging methods, then I lost permission to access edit my files in the server (I'm using cyberduck, I have another site that I can access just fine). I was also not using the API Keys for my SMTP username and password, which was suggested by a rep from postmark, but I didn't get to test the effects of changing that because of the permission issue. I still get a redirect to GitHub's PHPMailer download area when I submit my form (although it's not displaying directly on my page anymore), and the GitHub logo is, weirdly, displaying next to my page title... I'm thinking maybe one of the file edits I made most recently tried to edit the GitHub page, which I obviously don't have permission to do, which then messed up the permissions to my own files on cyberduck. That's only a stab in the dark, because I have no idea how that would work, but I'm pretty stuck!!