Twe*_*eak 4 php email wordpress attachment names
我正在使用 wp_mail 通过我网站上的表单发送邮件。但是当我附加一些文件时,名称类似于“phpr0vAqT”或“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
}
Run Code Online (Sandbox Code Playgroud)
我认为问题来自: ['tmp_name'] ,但我不知道我可以更改什么,因为 wp_mail 需要路径。
然后,我正在这样做:
wp_mail($to, $subject, $message, $headers, $files);
Run Code Online (Sandbox Code Playgroud)
发送邮件。
谢谢。
要更改附件名称,您应该使用phpmailer_init操作来直接访问所PHPMailer使用的实例wp_mail(),而不是$files作为函数参数传递:
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');
Run Code Online (Sandbox Code Playgroud)
上面的方法是正确的,这里是一个如何在 php / wp 中做到这一点的示例。希望这可以帮助!
if(!empty($_FILES['upload-attachment']['tmp_name'])){
//rename the uploaded file
$file_path = dirname($_FILES['upload-attachment']['tmp_name']);
$new_file_uri = $file_path.'/'.$_FILES['upload-attachment']['name'];
$moved = move_uploaded_file($_FILES['upload-attachment']['tmp_name'], $new_file_uri);
$attachment_file = $moved ? $new_file_uri : $_FILES['upload-attachment']['tmp_name'];
$attachments[] = $attachment_file;
}
Run Code Online (Sandbox Code Playgroud)
完成附件后,您应该清理
unlink($attachment_file);
Run Code Online (Sandbox Code Playgroud)