如何向电子邮件发送多个附件


How to send multiple attachments to 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()函数相同)。我的问题是,我收到了一封带有附件的电子邮件,但文件名混乱,没有扩展名,所以很难打开它。我在这里做错了什么,我该如何修复它?

当您在PHP中上传文件时,它们会被上传到一个临时目录,并被赋予一个随机名称。这是存储在每个文件的"tmp_name"键中的内容。它还解释了为什么每个文件在通过电子邮件发送时都没有扩展名,因为它们只是作为文件存储在临时目录中。原始文件名存储在"name"键中。

处理这个问题的最简单方法是将文件重命名为相应的文件名,然后发送,因为WordPress似乎不支持第二个字段来为每个文件提供文件名。

$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

$attachments=array();

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

这对我来说对多个文件都很好!祝好运