Tweak
Tweak

Reputation: 187

Send multiple attachments with wp_mail in PHP

I'm trying to send multiple attachments with wp_mail() , after some issues of attachments names (it displayed something like phprTxfd.pdf instead of file_name.pdf), i succeeded to display the name of the attachment.

But when i'm trying to send multiple attachment, it only display the first attachment in the mail, and not the others.

Here is my code :

function my_custom_email_content_type( $content_type ) {
                return 'text/html';
            }

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


                $files = $_FILES[ 'fichier' ];

            $upload_overrides = array( 'test_form' => false );

                $attachments = array();

            foreach ( $files['name'] as $key => $value ) {
                if ( $files[ 'name' ][ $key ] ) {
                    $file = array(
                        'name'     => $files[ 'name' ][ $key ],
                        'type'     => $files[ 'type' ][ $key ],
                        'tmp_name' => $files[ 'tmp_name' ][ $key ],
                        'error'    => $files[ 'error' ][ $key ],
                        'size'     => $files[ 'size' ][ $key ]
                    );
                    $movefile = wp_handle_upload(
                        $file,
                        $upload_overrides
                    );
                    $attachments[] = $movefile[ 'file' ];
                }
            }

                add_filter(
                 'wp_mail_content_type',
                 'my_custom_email_content_type'
             );
    wp_mail($to, $subject, $message, $headers, $attachments);

I think the issue is coming that $files = $_FILES['fichier'] just save the first file in the variable.

I tried to put $files as an array, but it doesn't work.

Thanks.

EDIT:

print_r($files) display this :

Array ( [name] => Array ( [0] => logo1.png [1] => logo2.png ) [type] => Array ( [0] => image/png [1] => image/png ) [tmp_name] => Array ( [0] => C:\xamp\tmp\phpC62D.tmp [1] => C:\xamp\tmp\phpC62E.tmp ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 4440 [1] => 7830 ) )

when i'm trying to insert 2 or several files in my file input multiple.

Upvotes: 0

Views: 1133

Answers (1)

MacGreenbear
MacGreenbear

Reputation: 11

I was running into this same issue when I came across this post.

The OP was very close in determining their issue...I too set it up as above and didn't receive any of my attachments.

It turns out, you need to set the 'name' of the file submission field as an array. In the OP case it should be set to name='fichier[]'

Once I changed that, my multiple files came through.

Upvotes: 1

Related Questions