Mark C.
Mark C.

Reputation: 6450

Sending attachment(s) in email

I've never touched PHP, but was tasked with fixing an Intern's code..

I am trying to attach a file being uploaded to an email that I am sending. The email sends, but without the file. I am using PHPMailerAutoUpload.php (found on GitHub).

Here's the code I am using.

The attachment is being saved via move_uploaded_file

move_uploaded_file( $resume['tmp_name'] , $up_dir .basename( $random_var . '_wse_' . $resume['name'] ) )

Note: I have commented out the move_uploaded_file function to make sure I wasn't getting rid of the attachment.

        require_once('phpmailer/PHPMailerAutoload.php');
        $mail = new PHPMailer(true);
        $mail->IsSMTP();
        $mail->SMTPDebug = 2;
        $mail->SMTPAuth = false;
        $mail->Host = 'oursmtp';
        $mail->Port = 25;

        $mail->setFrom( $_POST['E-mail'] , $_POST['first_name'] . " " . $_POST['last_name'] );
        $mail->addAddress( '[email protected]' );
        $mail->Subject = "Test" . @date('M/D/Y');
        $mail->msgHTML($msgDoc);

        if (isset($_FILES['uploaded_file']) &&
        $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
        $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                             $_FILES['uploaded_file']['name']);
        }


        if (!$mail->send()) {
            $mailError = $mail->ErrorInfo;
            $outcomeArr = array(
                                'outcome'=>'failure',
                                'message'=>'Error' . $mailError
                            );              
            echo json_encode( $outcomeArr );
            exit();             
        } else {
            // success
            $outcomeArr = array(
                                'outcome'=>'success',
                                'message'=>'Thank you'
                            );      
            echo json_encode( $outcomeArr );
        }

From what I have read, $_FILES is a temporary storage for uploaded files in PHP. With this code, the email sends, but with no attachment (only a link to the uploaded file location).

I tried following this, but it isn't working for me.

Upvotes: 0

Views: 533

Answers (1)

Sammitch
Sammitch

Reputation: 32232

Your intern was apparently a rockstar that had no need to check for or indicate error conditions, and then mail will send even if there's no attachment or if there was an error during the upload. Change these bits to the code to tell you why the file wasn't attached:

if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    if( ! $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'], $_FILES['uploaded_file']['name']) ) {
        echo 'Error adding attachment: ' . $mail->ErrorInfo;
    }
} else if( !isset($_FILES['uploaded_file']) ) {
    echo 'No uploaded file found';
} else {
    echo 'Uploaded file error: ' . $_FILES['uploaded_file']['error'];
}

Upvotes: 1

Related Questions