Laravel 5.3 - 将多个文件附加到 Mailables

Laravel 5.3 - Attach Multiple Files To Mailables

如何将多个文件附加到 laravel 5.3 可邮寄?

我可以在我的可邮寄构建方法中使用 ->attach($form->filePath) 轻松地附加一个文件。但是,当我将表单字段更改为数组时,我收到以下错误:

basename() expects parameter 1 to be string, array given

我已经在堆栈上搜索了文档和各种搜索词,但均无济于事。任何帮助将不胜感激。

构建方法:

public function build()
{
    return $this->subject('Employment Application')
                ->attach($this->employment['portfolio_samples'])
                ->view('emails.employment_mailview');
}

来自控制器的邮件调用:

Mail::to(config('mail.from.address'))->send(new Employment($employment));

您应该将生成的电子邮件存储为变量,然后您可以像这样添加多个附件:

public function build()
{
    $email = $this->view('emails.employment_mailview')->subject('Employment Application');
    
    // $attachments is an array with file paths of attachments
    foreach ($attachments as $filePath) {
        $email->attach($filePath);
    }

    return $email;
}

在这种情况下,您的 $attachments 变量应该是一个包含文件路径的数组:

$attachments = [
    // first attachment
    '/path/to/file1',

    // second attachment
    '/path/to/file2',
    ...
];

此外,您不仅可以通过文件路径附加文件,还可以使用 MIME 类型和所需的文件名附加文件,请参阅有关“附件”方法的第二种使用情况的文档:https://laravel.com/docs/master/mail#attachments

例如,您的 $attachments 数组可以是这样的:

$attachments = [
    // first attachment
    'path/to/file1' => [
        'as' => 'file1.pdf',
        'mime' => 'application/pdf',
    ],
    
    // second attachment
    'path/to/file12' => [
        'as' => 'file2.pdf',
        'mime' => 'application/pdf',
    ],
    
    ...
];

您可以附加此数组中的文件后:

// $attachments is an array with file paths of attachments
foreach ($attachments as $filePath => $fileParameters) {
    $email->attach($filePath, $fileParameters);
}

最适合我的解决方案

$email = $this->from($from)->subject("Employment Application")
    ->view('emails.employment_mailview');

foreach ($files as $file) {
    $path = '/path/to/'.$file->file;
    $attachments->push($path);
}

$attachments = collect([]);

foreach ($attachments as $filePath) {
    $email->attach($filePath);
}

return $email;