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

Dennis Planner
Dennis Planner
2,914 Points

PHPMailer contact form - Adding Attachments doesn't work

Hello all,

I'm making grounds thanks to Treehouse, on a contact form I'm working on for a personal site.

I'm using the PHPMailer library and I'd like to have the ability to attach a file on the form.

The actual input HTML element nested in the form element is:

<input type ="file" name='attachment' id='uploaded_file'>

From my readings, I found out that once I've press the submit button, the file should now be stored in $_FILES using the Post method. Fair enough, so I'd assume that the actually file can be returned using $_FILES['uploaded_file'] that uses the id of the input element

There is a method called addAttachment that in its simplest form, accepts the path name as the argument.

I pass this method through to the PHPMailer() instance of the object, $mail as so:

$mail->addAttachment($_FILES['uploaded_file']);

...After the $mail instantiation, and before the send() function.

The email sends, but I don't receive any attachment to the mail. Strange, one any ideas that can help me?

Here is the code

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// CLASS DECLARATIONS

require_once("includes/PHPMailer/class.phpmailer.php");
require_once('/includes/PHPMailer/PHPMailerAutoload.php');
$mail = new PHPMailer();

// VARIABLE DECLARATIONS

$errName = '';
$errEmail = '';
$errMessage = '';
$error = false;



if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]); //trim destroys whitespaces like "Tab" or "Spacebar"
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);

    // Attack #1 preventor - Spam Honeypot

    if ($_POST["address"] != "") {
        echo "SPAM HONEYPOT";
        exit;
    }

    // Attack #2 preventor - Email header injection hack preventor 

    foreach($_POST as $value) {
        if(stripos($value, 'Content-Type:') !== FALSE) {
            echo "There was a problem with the information you entered.";
            exit;
        }
    }

     // Check if name has been entered
    if ($name == "") {
        $errName = 'Sorry, you have not entered a name, please try again.';             
    }

    // Check if message has been entered
    if ($message == "") {      
        $errMessage = 'Sorry, you have not typed a message.';      
    }

    // Check if email is valid
    if (!$mail->validateAddress($email)) {        
        $errEmail = 'Sorry, please enter a valid email address.';
    }

    // Flag error messages if any tests fail

    if ($errName || $errMessage || $errEmail) {
        $error = true; // Boolean to flag validating error messages in the HTML
    } 
    else {             


        // EMAIL BODY IFF FORM VALIDATION IS SUCESSFULL! 
        $email_body = "";
        $email_body = $email_body. "Name: " . $name . "<br>";
        $email_body = $email_body. "Email: " . $email . "<br>";
        $email_body = $email_body. "Message: " . $message;


        date_default_timezone_set('Etc/UTC');


        //Tell PHPMailer to use SMTP
        $mail->isSMTP();

        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->SMTPDebug = 2;

        //Ask for HTML-friendly debug output
        $mail->Debugoutput = 'html';

        //Set the hostname of the mail server
        $mail->Host = 'smtp.gmail.com';

        //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
        $mail->Port = 587;

        //Set the encryption system to use - ssl (deprecated) or tls
        $mail->SMTPSecure = 'tls';

        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;

        //Username to use for SMTP authentication - use full email address for gmail
        $mail->Username = "#############################";

        //Password to use for SMTP authentication
        $mail->Password = "###################";

        //Set who the message is to be sent from
        $mail->setFrom($email, $name);

        //Set who the message is to be sent to
        $mail->addAddress('perpetualprinting@gmail.com', 'John Doe');

        //Set the subject line
        $mail->Subject = 'PHPMailer GMail SMTP test';

        //Add attachment
        $mail->addAttachment($_FILES['uploaded_file']);
//        if (isset($_FILES['uploaded_file']) &&
//            $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
//            $mail->addAddress($_FILES['uploaded_file']['tmp_name'],
//                                 $_FILES['uploaded_file']['name']);
//        }


        //Read an HTML message body from an external file, convert referenced images to embedded,
        //convert HTML into a basic plain-text alternative body
        $mail->msgHTML($email_body);


        //send the message, check for errors
        if (!$mail->send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        }
        else {             
        }
        header("Location: contact.php?status=thanks");
        exit;
    }
}
?>

And the HTML

<html>
    <head>
        <?php include('includes/bootstrap.php'); ?>
        <title>Imperial 3D | Contact Us</title>       
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->              
    </head>

    <body>       
        <div class = 'container'>          
            <!--navbar-->           
            <nav class="navbar navbar-default navbar-inverse">
                <?php include('includes/navbar.php'); ?>                    
            </nav>           
            <!--body-->         
            <div class = "wrapper">   
                <section class ="bulk"
                    <div class ="row">

                    <?php if(isset($_GET["status"]) == "thanks") { ?>
                        <br><br><br><br><br><br><br><br><br><br><br><br>
                        <p class = "text-center"> Thanks for the email! I'll be in touch shortly </p>
                    <?php } else { ?>
                        <h1 class = "text-center">
                            Contact
                        </h1>                        
                        <p class = "text-center">
                            We'd love to hear from you! Complete the form to contact me. 
                        </p>

                    <!-- form stuff -->                                         
                        <div class ="row">                        
                            <div class ='col-md-6'>                                                                                                                              
                                <form method ="post" action ="contact.php" enctype='multipart/form-data'>
                                    <div class="form-group">
                                         <label for="name">Name</label>
                                        <input type ="text" class="form-control" name="name" id ="name" placeholder="Enter name" value="<?php if (!empty($_POST['name'])) {echo $_POST['name'];} ?>">                                           
                                        <?php 
                                            if ($error) {
                                                echo "<p class='text-danger'>$errName</p>";
                                            }
                                            else {
                                                echo "<br>";
                                            }                                           
                                        ?>
                                    </div>                                                                                                                                                                         
                                    <!--email-->
                                    <div class="form-group">
                                        <label for="email">Email</label>
                                        <input type ="text" class="form-control" name="email" id ="email" placeholder="Enter email" value="<?php if (!empty($_POST['email'])) {echo $_POST['email'];} ?>">
                                        <?php 
                                            if ($error) {
                                                echo "<p class='text-danger'>$errEmail</p>";
                                            }
                                            else {
                                                echo "<br>";
                                            }                                           
                                        ?>
                                    </div>   
                                    <!--msg-->
                                    <div class="form-group">
                                        <label for="message">Message</label>                                            
                                        <textarea name ="message" class="form-control" id ="message" placeholder="Enter message" rows = "10" ></textarea>
                                        <?php 
                                            if ($error) {
                                                echo "<p class='text-danger'>$errMessage</p>";
                                            }
                                            else {
                                                echo "<br>";
                                            }                                           
                                        ?>
                                    </div> 
                                    <!--attachments-->
                                    <div class="form-group">
                                        <label for="attachment" >Attachment</label>                                            
                                        <input type ="file" name='attachment' id='uploaded_file'>
                                    </div>
                                    <!--Hpam Sponypot -->
                                    <div class="form-group" style="visibility: hidden">     
                                        <label for="address">Address</label>
                                        <input type ="text" name="address" id ="address">  
                                        <p> Humans, do not fill out this form! </p>
                                    </div>                                     
                                    <!--attachments-->
                                    <button type="submit" value="Send" class="btn btn-default">Submit</button>
                            </form>
                        </div>

                    <!-- contact details -->
                    <div class ='col-md-6'>
                        <h3> Contact Details </h3>
                        <ul class = "contact-info">
                            <li>Dennis.</li>
                            <li class ="phone"><span class="glyphicon glyphicon-earphone"></span><span><?php echo"   Tel: " ?></span><a href ="tel:04040404">04040404</a></li>
                        </ul>
                    </div>
                </div> 
                    <?php } ?>
                </section>                
                <div class ="pusher">
                <?php include('includes/footer.php'); ?>  
                </div>
            </div>                     
        </div>       
    </body>
</html>

Cheers :) Dennis

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Dennis,

You have a simple typo which is your code is referencing uploaded_file which isn't the name for your upload field, instead this should be attachment as that's the value in your name attribute.

$mail->addAttachment($_FILES['attachment']);

Happy coding!

Dennis Planner
Dennis Planner
2,914 Points

Cheers Chris! You're absolutely right.