Attach file email laravel

In Laravel, you can attach files to an email using the Mailable class and the attach method. Here's an example:

Step 1: Create a Mailable class

Create a new file in the app/Mail directory, e.g., MyEmail.php. This file will contain the logic for sending the email.

// app/Mail/MyEmail.php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class MyEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $data;

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

    public function build()
    {
        return $this->view('emails.my-email');
    }
}

Step 2: Create a view for the email

Create a new file in the resources/views/emails directory, e.g., my-email.blade.php. This file will contain the HTML for the email.

<!-- resources/views/emails/my-email.blade.php -->

<h1>My Email</h1>

<p>Hello, {{ $data['name'] }}!</p>

<p>Here is the attached file:</p>

<a href="{{ $data['file']->url }}">Download File</a>

Step 3: Attach the file

In the MyEmail class, use the attach method to attach the file to the email.

// app/Mail/MyEmail.php

public function build()
{
    $file = storage_path('app/files/my-file.pdf'); // path to the file
    return $this->view('emails.my-email')
        ->attach($file, ['as' => 'my-file.pdf', 'mime' => 'application/pdf']);
}

In this example, we're attaching a file named my-file.pdf from the storage/app/files directory. You can adjust the path and file name as needed.

Step 4: Send the email

To send the email, you can use the Mail::send method in a controller or a scheduled task.

// app/Http/Controllers/MyController.php

public function sendEmail()
{
    $data = ['name' => 'John Doe', 'file' => 'my-file.pdf'];
    Mail::send(new MyEmail($data));
}

That's it! When you run the sendEmail method, Laravel will send the email with the attached file.

Note: Make sure to configure your email settings in the config/mail.php file and set up a mail driver (e.g., smtp, sendmail, or mailgun) to send the email.