简体   繁体   中英

Send attachment to email using wp_mail

I am using wordpress 4.4.2.

Code of form for file type:

<input placeholder="'.__( 'Select File', 'mk_framework' ).'" type="file" name="file" id="file" class="contact_file file-form select-input full"/>

I have used following code for upload file and send attachment to email.

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 && ! isset( $movefile['error'] ) ) {
  echo "File is valid, and was successfully uploaded.\n";
  var_dump( $movefile );
  $attachments = $movefile[ 'file' ];
} else {
  echo $movefile['error'];
}

wp_mail($to, $subject, $body, $headers, $attachments);

I have also increase size of 'upload_max_filesize and 'post_max_size' variables in php.ini but can't get an attachment to email.

But still it will giving me error like:

File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.

So is there any way to do this? Any help/suggestion would be appreciated.

Late Answer;

You need to change the upload folder permission

like

chown -R www-data:www-data /var/www/html

the you need to use array for attchement.

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 && ! isset( $movefile['error'] ) ) {
  echo "File is valid, and was successfully uploaded.\n";
  var_dump( $movefile );
  $attachments = array($movefile[ 'file' ]);
} else {
  echo $movefile['error'];
}

wp_mail($to, $subject, $body, $headers, $attachments);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM