简体   繁体   English

更改附件名称:wp_mail PHP

[英]Change names of attachments : wp_mail PHP

I'm using wp_mail to send mails with a form which is on my website. 我正在使用wp_mail通过网站上的表单发送邮件。 But when i attach some files, names are like "phpr0vAqT" or "phpFO0ZoT". 但是当我附加一些文件时,名称就像“ 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

         }

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. 我认为问题出在:['tmp_name'],但是我不知道我可以更改什么,因为wp_mail需要路径。

Then, i'm doing this : 然后,我正在这样做:

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

to send the mail. 发送邮件。

Thanks. 谢谢。

You cannot change attachment names with wp_mail. 您不能使用wp_mail更改附件名称。

A possible solution is: 可能的解决方案是:

  1. save the files with the correct name. 用正确的名称保存文件。
  2. send the new files with wp_mail. 使用wp_mail发送新文件。
  3. remove the files. 删除文件。

The above approach is correct, here is an example of how you can do that in php / wp. 上面的方法是正确的,这是一个如何在php / wp中执行此操作的示例。 Hope this helps! 希望这可以帮助!

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;
 }

And after finish with the attachment, you should clean up 在完成附件后,您应该清理

unlink($attachment_file);

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: 要更改附件名称,您应该使用phpmailer_init操作直接访问wp_mail()使用的PHPMailer实例,而不是将$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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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