diff --git a/src/Illuminate/Mail/Attachment.php b/src/Illuminate/Mail/Attachment.php index f49d32cc1e78..8e2e87ed5496 100644 --- a/src/Illuminate/Mail/Attachment.php +++ b/src/Illuminate/Mail/Attachment.php @@ -5,6 +5,7 @@ use Closure; use Illuminate\Container\Container; use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Traits\Macroable; use RuntimeException; @@ -79,6 +80,23 @@ public static function fromData(Closure $data, $name = null) ))->as($name); } + /** + * Create a mail attachment from an UploadedFile instance. + * + * @param \Illuminate\Http\UploadedFile $file + * @return static + */ + public static function fromUploadedFile(UploadedFile $file) + { + return new static(function ($attachment, $pathStrategy, $dataStrategy) use ($file) { + $attachment + ->as($file->getClientOriginalName()) + ->withMime($file->getMimeType() ?? $file->getClientMimeType()); + + return $dataStrategy(fn () => $file->get(), $attachment); + }); + } + /** * Create a mail attachment from a file in the default storage disk. * diff --git a/src/Illuminate/Mail/composer.json b/src/Illuminate/Mail/composer.json index 6f976a9e45dc..8df873951555 100755 --- a/src/Illuminate/Mail/composer.json +++ b/src/Illuminate/Mail/composer.json @@ -37,6 +37,7 @@ }, "suggest": { "aws/aws-sdk-php": "Required to use the SES mail driver (^3.322.9).", + "illuminate/http": "Required to create an attachment from an UploadedFile instance (^12.0).", "resend/resend-php": "Required to enable support for the Resend mail transport (^0.10.0).", "symfony/http-client": "Required to use the Symfony API mail transports (^7.2).", "symfony/mailgun-mailer": "Required to enable support for the Mailgun mail transport (^7.2).", diff --git a/tests/Mail/AttachableTest.php b/tests/Mail/AttachableTest.php index d6e928c7f2b6..356160a965fe 100644 --- a/tests/Mail/AttachableTest.php +++ b/tests/Mail/AttachableTest.php @@ -3,6 +3,7 @@ namespace Illuminate\Tests\Mail; use Illuminate\Contracts\Mail\Attachable; +use Illuminate\Http\Testing\File; use Illuminate\Mail\Attachment; use Illuminate\Mail\Mailable; use PHPUnit\Framework\TestCase; @@ -138,4 +139,34 @@ public function toMailAttachment() ], ], $mailable->attachments[0]); } + + public function testFromUploadedFileMethod() + { + $mailable = new class extends Mailable + { + public function build() + { + $this->attach(new class implements Attachable + { + public function toMailAttachment() + { + return Attachment::fromUploadedFile( + File::createWithContent('example.pdf', 'content') + ->mimeType('application/pdf') + ); + } + }); + } + }; + + $mailable->build(); + + $this->assertSame([ + 'data' => 'content', + 'name' => 'example.pdf', + 'options' => [ + 'mime' => 'application/pdf', + ], + ], $mailable->rawAttachments[0]); + } }