Adding an Attachment to Contact Form Using wp_mail

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?

1 Answer
1

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['uploaded_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">

Leave a Comment