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.
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');
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With