4

Would anyone be kind enough to explain to me how to attach an uploaded file to an email generated using wp_mail? I've built the form but all the questions I can find online refer to attaching a pre-determined file rather than one uploaded by the user.

EDIT I'm now trying to use wp_handle_upload:

if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
  echo "File is valid, and was successfully uploaded.\n";
  var_dump( $movefile);
} else {
  echo "Possible file upload attack!\n";
}

...but am getting the following error: "File is empty. Please upload something more substantial..." Which I think is because I'm not passing the attachment variable in correctly.

My form field looks like:

<input type="file" name="uploaded_picture">

Could anyone point out how I tie these two together please?

  • You can check out the form in use at salt.nugerama.co.uk/jobs – Kevin Nugent Nov 2 '14 at 20:01
  • Is this related to Wordpress? – Gangesh Nov 2 '14 at 20:10
  • Yes Gangesh. It's a template for a WordPress theme with a contact for on it. – Kevin Nugent Nov 2 '14 at 20:27
3

In short, I was simply failing to pass in the correct variable:

if ( ! function_exists( 'wp_handle_upload' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
}

$uploadedfile       = $_FILES['file'];
$upload_overrides   = array( 'test_form' => false );
$movefile           = wp_handle_upload( $uploadedfile, $upload_overrides );

if( $movefile ) {
    //echo "File is valid, and was successfully uploaded.\n";
    //var_dump( $movefile);
    $attachments = $movefile[ 'file' ];
    wp_mail($to, $subject, strip_tags($message), $headers, $attachments);
} else {
    echo "Possible file upload attack!\n";
}

My form field should have been:

<input type="file" name="uploaded_file" accept="application/pdf">
  • Great that you could solve the problem! Please mark your answer as solved using the ✔. – shea Dec 12 '14 at 10:01
  • it seems that it should not work becuase at you html the name of input is not file. Or at your php code you should replace file to uploaded_file – Dmitry Shulga Jun 26 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.