如何将多个附件发送到电子邮件

时间:2016-05-03 16:37:18

标签: php wordpress email

我有以下简单的表单,可以将多个文件发送到电子邮件:

<form method="post" enctype="multipart/form-data">
            <input id="upload-file" class="upload-file" type="file" name="my_file[]" multiple>
            <input type="submit" value="Send">
        </form>

我使用以下php代码进行实际发送:

if (isset($_FILES['my_file'])) {
        $to = 'my-email@maybe-gmail.com';
        $subject = 'Files moar files';
        $message = 'Message Body';
        $headers = 'Some random email header';
        $attachments = array();
                $myFile = $_FILES['my_file'];
                $fileCount = count($myFile["name"]);
                for ($i = 0; $i < $fileCount; $i++) {

                   $attachments[$i] = $_FILES['my_file']['tmp_name'][$i];
                }
        wp_mail($to, $subject, $message, $headers, $attachments);
            }

我使用的是wp_mail()方法,因为这是在Wordpress网站上(它与php mail()函数相同)。 我的问题是,我收到一封带有附件的电子邮件,但是文件的名称搞砸了,没有扩展名,所以很难打开它。我在这里做错了什么,我该如何解决?

2 个答案:

答案 0 :(得分:2)

当您使用PHP上传文件时,它们会上传到临时目录并以随机名称提供。这是存储在&#39; tmp_name&#39;每个文件的密钥。它还解释了为什么每个文件在通过电子邮件发送时都没有扩展名,因为它们只是作为文件存储在临时目录中。原始文件名存储在&#39;名称&#39;键。

解决此问题的最简单方法是将文件重命名为适当的文件名,然后发送它们,因为看起来WordPress似乎不支持第二个字段来为每个文件提供文件名。 / p>

$uploaddir = '/var/www/uploads/'; //Or some other temporary location
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
    $uploadfile = $uploaddir . basename($_FILES['my_file']['name'][$i]);
    if (!move_uploaded_file($_FILES['my_file']['tmp_name'][$i], $uploadfile)) {
        //If there is a potential file attack, stop processing files.
        break;
    }
    $attachments[$i] = $uploadfile;

}
wp_mail($to, $subject, $message, $headers, $attachments);

//clean up your temp files after sending
foreach($attachments as $att) {
    @unlink($att);
}

在处理文件时,验证MIME类型并限制您支持的文件类型也是一种很好的做法。

WordPress wp_mail:https://developer.wordpress.org/reference/functions/wp_mail/ PHP POST上传:http://php.net/manual/en/features.file-upload.post-method.php

答案 1 :(得分:0)

  

$ attachments = array();

     

array_push($ attachments,WP_CONTENT_DIR。   '/uploads/my-document.pdf'); array_push($附件,   WP_CONTENT_DIR。 '/uploads/my-file.zip');

对于多个文件,它对我有用! 祝你好运