How to add attachment in laravel email?

Member

by dedrick , in category: PHP General , a year ago

How to add attachment in laravel email?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a year ago

@dedrick 

To add an attachment in Laravel email, you can use the attach() method provided by the Mailable class.


Here is an example of how you can add an attachment to an email:

  1. Create a new Mailable class by running the following command in your terminal:
1
php artisan make:mail SendAttachment


  1. In the SendAttachment class, define the necessary variables and import the IlluminateMailMailable class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use IlluminateMailMailable;

class SendAttachment extends Mailable
{
    public $attachmentPath;

    public function __construct($attachmentPath)
    {
        $this->attachmentPath = $attachmentPath;
    }

    public function build()
    {
        return $this->view('emails.send_attachment')
            ->attach($this->attachmentPath);
    }
}


  1. Create a blade template file named send_attachment.blade.php in the resources/views/emails directory. This will contain the email content.
  2. Use the SendAttachment class to send the email:
1
2
3
4
5
6
7
use AppMailSendAttachment;
use IlluminateSupportFacadesMail;

$attachmentPath = storage_path('app/attachments/file.pdf'); // Path to the attachment file

Mail::to('[email protected]')
    ->send(new SendAttachment($attachmentPath));


Replace '[email protected]' with the email address of the recipient.


Make sure to update the storage_path('app/attachments/file.pdf') to the actual path of your attachment file.


That's it! When the email is sent, the attachment file will be included in the email.