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 Build a Simple PHP Application Wrapping Up The Project Sending The Contact Form Email

PHPMailer's if(!mail->send()) not working

seems like everything is set in place, but once i add this code in:

if(!mail->send()) {
        echo "There was a problem sending the email: " . $mail->ErrorInfo;
        exit;
    }

my page no longer loads.

what do you guys think?

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

    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $message = trim($_POST['message']);

    if ($name == "" OR $email == "" OR $message == ""){echo "Please type your name, email, and message before sending me your message."; exit; }
    foreach($_POST as $value){ if(stripos($value, 'Content-Type:') !== FALSE){ exit; }}
    if ($_POST['address'] != ""){exit;}

    require_once('[library]/link/php/phpmailer/class.phpmailer.php');

    $mail = new PHPMailer();

    if(!$mail->ValidateAddress($email)){
        echo "Please specify a valid e-mail address, so I can contact you.";
    }

    $emailbody = "";
    $emailbody = $emailbody . "Name: " . $name . "<br>";
    $emailbody = $emailbody . "E-mail: " . $email . "<br>";
    $emailbody = $emailbody . "Message: " . $message;
    //
    $mail->SetFrom($email,$name);
    $address = "here@nin-yo.com";
    $mail->AddAddress($address, "Ninyo!");
    $mail->Subject = "Nin-yo.com Contact Form Submission | ".$name;
    $mail->MsgHTML($email_body);

    if(!mail->send()) {
        echo "There was a problem sending the email: " . $mail->ErrorInfo;
        exit;
    }

//I also tried Send() as opposed to send() 

    header("Location: index.php?status=thanksman");
    exit;
}

I hope you guys can help thanks a lot!

1 Answer

Conor Haining
Conor Haining
2,193 Points

You haven't referenced the variable $mail

if(!$mail->send()){ ... }

beautiful! such a simple mistake. thank you very much