在PHPMailer中添加多个附件

时间:2015-03-13 12:20:03

标签: php attachment email-attachments mailer

我正在尝试在附件中附加多个图像。我使用forearch作为每个附件但是,当我使用foreach时它没有得到临时名称和名字,我可能做错了。以下是代码和错误:

输入HTML

<input id="upload-file" class="upload-file" type="file" name="upload-file[]">

var_dump $ _FILES ['upload-file']:

array(5) { ["name"]=> array(1) { [0]=> string(47) "WRANGLER_AW13_GIRLONTOP_A4_LANDSCAPE_300dpi.jpg" } ["type"]=> array(1) { [0]=> string(10) "image/jpeg" } ["tmp_name"]=> array(1) { [0]=> string(24) "C:\xampp\tmp\php41DC.tmp" } ["error"]=> array(1) { [0]=> int(0) } ["size"]=> array(1) { [0]=> int(91742) } } 

名称和temp_name的var_dump:

Notice: Undefined index: name in C:\xampp\htdocs\hmg\process-email.php on line 66

Notice: Undefined index: tmp_name in C:\xampp\htdocs\hmg\process-email.php on line 67

NULL 
NULL

CODE:

foreach($_FILES['upload-file'] as $file) {         

    $name = $file['name'];
    $path = $file['tmp_name'];
    var_dump($name);
    var_dump($path);

    //And attach it using attachment method of PHPmailer.

    $mail->addattachment($path,$name);
}

4 个答案:

答案 0 :(得分:7)

欢迎来到PHP的邪恶方面。 $_FILES不是那个,开发人员所期望的。

//wrong code
$img1 = $_FILES['upload-file'][0]['tmp_name'];
$img2 = $_FILES['upload-file'][1]['tmp_name'];

//working code
$img1 = $_FILES['upload-file']['tmp_name'][0];
$img2 = $_FILES['upload-file']['tmp_name'][1];

所以你需要像

这样的东西
$totalFiles = count($_FILES['upload-file']['tmp_name']);
for ($i = 0; $i < $totalFiles; $i++) {
   $name = $_FILES['upload-file']['name'][$i];
   $path = $_FILES['upload-file']['tmp_name'][$i];
   $mail->addattachment($path,$name);
}

这是来自PHPMailer存储库的some example

答案 1 :(得分:2)

感谢所有答案。我相信你所有的方法都可以正常工作,但我决定自己解决。这段代码解决了这个问题

$validAttachments = array();

foreach($_FILES['upload-file']['name'] as $index => $fileName) {
    $filePath = $_FILES['upload-file']['tmp_name'][$index];
    $validAttachments[] = array($filePath, $fileName);              
}

foreach($validAttachments as $attachment) {
    $mail->AddAttachment($attachment[0], $attachment[1]);
}

我希望有同样问题的人从这里得到一些帮助......

答案 2 :(得分:0)

$i = '0';
foreach($_FILES['upload-file'] as $file) {
$name = $file['name'][$i];
$path = $file['tmp_name'][$i];
var_dump($name);
var_dump($path);
$mail->addattachment($path,$name);
$i++;
}

答案 3 :(得分:0)

此处的大部分解决方案均基于表格。

如果你想附加特定目录中的所有文件,我想出了一个简单的解决方案。

$file_to_attach_directory = 'files/';
if ($handle = opendir($file_to_attach_directory)) {
    try {
        while (false !== ($entry = readdir($handle))) {
            $attachment_location = $file_to_attach_directory. $entry;
            $mail->addAttachment($attachment_location);
        }
        closedir($handle);
        // Send Mail
        if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Message sent!";
        }
    } catch (Exception $e) {
        var_dump($e);
    }
}