Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Illuminate/Mail/Attachment.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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.
*
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Mail/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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).",
Expand Down
31 changes: 31 additions & 0 deletions tests/Mail/AttachableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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]);
}
}