Skip to content

Commit 8a2b817

Browse files
[9.x] Ability to attach an array of files in MailMessage (#43080)
* Ability to attach an array of files in MailMessage Passing a filepath or an array of filepaths will now attach one or multiple files in mail. * Update Mailable.php * created attachMany method instead of using attach The method will take filename, array of filenames or attachable object as input and modify it to pass through current attach method. * fixed typo * formatting * add tests * formatting * formatting Co-authored-by: Tim MacDonald <[email protected]>
1 parent 5d34d92 commit 8a2b817

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Illuminate/Mail/Mailable.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,25 @@ public function attach($file, array $options = [])
890890
return $this;
891891
}
892892

893+
/**
894+
* Attach multiple files to the message.
895+
*
896+
* @param array $files
897+
* @return $this
898+
*/
899+
public function attachMany($files)
900+
{
901+
foreach ($files as $file => $options) {
902+
if (is_int($file)) {
903+
$this->attach($options);
904+
} else {
905+
$this->attach($file, $options);
906+
}
907+
}
908+
909+
return $this;
910+
}
911+
893912
/**
894913
* Attach a file to the message from storage.
895914
*

tests/Mail/MailMailableTest.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,43 @@ public function testMailableTagGetsSent()
497497
$this->assertStringContainsString('X-Tag: foo', $sentMessage->toString());
498498
}
499499

500+
public function testItCanAttachMultipleFiles()
501+
{
502+
$mailable = new WelcomeMailableStub;
503+
504+
$mailable->attachMany([
505+
'/forge.svg',
506+
'/vapor.svg' => ['as' => 'Vapor Logo.svg', 'mime' => 'text/css'],
507+
new class() implements Attachable
508+
{
509+
public function toMailAttachment()
510+
{
511+
return Attachment::fromPath('/foo.jpg')->as('bar')->withMime('image/png');
512+
}
513+
},
514+
]);
515+
516+
$this->assertCount(3, $mailable->attachments);
517+
$this->assertSame([
518+
'file' => '/forge.svg',
519+
'options' => [],
520+
], $mailable->attachments[0]);
521+
$this->assertSame([
522+
'file' => '/vapor.svg',
523+
'options' => [
524+
'as' => 'Vapor Logo.svg',
525+
'mime' => 'text/css',
526+
],
527+
], $mailable->attachments[1]);
528+
$this->assertSame([
529+
'file' => '/foo.jpg',
530+
'options' => [
531+
'as' => 'bar',
532+
'mime' => 'image/png',
533+
],
534+
], $mailable->attachments[2]);
535+
}
536+
500537
public function testItAttachesFilesViaAttachableContractFromPath()
501538
{
502539
$mailable = new WelcomeMailableStub;

0 commit comments

Comments
 (0)