Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change names of attachments : wp_mail PHP

I'm using wp_mail to send mails with a form which is on my website. But when i attach some files, names are like "phpr0vAqT" or "phpFO0ZoT".

$files = array(); //Array pour les fichiers
$count = count(array_filter($_FILES['fichier']['name'])); //Compte le nombre de fichiers

        for($i=0;$i<$count;$i++){ //boucle sur chaque fichier

            array_push($files, $_FILES['fichier']['tmp_name'][$i]); //insere le fichier dans l'array $files

         }

I think the issue is coming from the : ['tmp_name'] , but i don't know what can i change because wp_mail need a path.

Then, i'm doing this :

wp_mail($to, $subject, $message, $headers, $files);

to send the mail.

Thanks.

like image 203
Tweak Avatar asked Oct 18 '25 17:10

Tweak


2 Answers

To change attachment names you should use phpmailer_init action for direct access to PHPMailer instance used in wp_mail() instead of passing $files as function parameter:

function prefix_phpmailer_init(PHPMailer $phpmailer) {
    $count = count($_FILES['fichier']['tmp_name']); //Count the number of files
    for ($i = 0; $i < $count; $i++) { //loop on each file
        if (empty($_FILES['fichier']['error'][$i]))
            $phpmailer->addAttachment($_FILES['fichier']['tmp_name'][$i], $_FILES['fichier']['name'][$i]); //Pass both path and name
    }
}

add_action('phpmailer_init', 'prefix_phpmailer_init');
wp_mail($to, $subject, $message, $headers);
remove_action('phpmailer_init', 'prefix_phpmailer_init');
like image 56
AndreyP Avatar answered Oct 21 '25 08:10

AndreyP


Since WP 6.2 you can set the filenames as keys of the array:

$attachments = [
    'filename1.txt'  => '/path/to/the/file1',
    'file_name2.pdf' => '/path/to/file2',
];

wp_mail( $to, $subject, $message, $headers, $attachments );
like image 39
d79 Avatar answered Oct 21 '25 08:10

d79