diff --git a/src/Event/PostSubmitEvent.php b/src/Event/PostSubmitEvent.php index bf3fc0a..7927802 100644 --- a/src/Event/PostSubmitEvent.php +++ b/src/Event/PostSubmitEvent.php @@ -7,6 +7,7 @@ use Bolt\BoltForms\BoltFormsConfig; use Carbon\Carbon; use Symfony\Component\Form\Form; +use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Contracts\EventDispatcher\Event; use Tightenco\Collect\Support\Collection; @@ -40,6 +41,34 @@ public function __construct(Form $form, BoltFormsConfig $config, string $formNam $this->formName = $formName; $this->request = $request; $this->attachments = collect([]); + + $formConfig = $config->getConfig()->get($formName); + if ($formConfig["attach"] ?? false) { + foreach ($formConfig["fields"] as $field => $fieldConfig) { + if ($fieldConfig["type"] !== "file") { + continue; + } + + $files = $form->get($field)->getData(); + if (!is_iterable($files)) { + $files = [$files]; + } + foreach ($files as $file) { + if (!$file instanceof UploadedFile || $file->getError()) { + continue; + } + + $item = [ + "content" => $file->getContent(), + "filename" => $file->getClientOriginalName(), + "mimetype" => $file->getMimeType(), + ]; + $this->attachments->add( + $item + ); + } + } + } } public function getFormName(): string diff --git a/src/Factory/EmailFactory.php b/src/Factory/EmailFactory.php index 2576e6a..b55b4b4 100644 --- a/src/Factory/EmailFactory.php +++ b/src/Factory/EmailFactory.php @@ -5,9 +5,9 @@ namespace Bolt\BoltForms\Factory; use Bolt\Common\Str; -use File; use Symfony\Bridge\Twig\Mime\TemplatedEmail; use Symfony\Component\Form\Form; +use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Mime\Address; use Tightenco\Collect\Support\Collection; @@ -67,10 +67,11 @@ public function create(Collection $formConfig, Collection $config, Form $form, a $email->replyTo($this->getReplyTo()); } - foreach ($attachments as $name => $attachment) { - /** @var File $attachment */ - foreach ($attachment as $file) { - $email->attachFromPath($file, $name . '.' . pathinfo($file, PATHINFO_EXTENSION)); + foreach ($attachments as $attachment) { + try { + $email->attach($attachment["content"], $attachment["filename"], $attachment["mimetype"]); + } catch (\Exception $e) { + // Re-submit of the form will have an "empty" file, for example. } }