How to attach a file while sending mail laravel

In Laravel, you can attach a file while sending a mail 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., MyMail.php. In this file, extend the Mailable class:

namespace App\Mail;

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

class MyMail extends Mailable
{
    use Queueable, SerializesModels;

    public $file;

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

    public function build()
    {
        return $this->view('emails.my-mail')
            ->attach($this->file, ['as' => 'my-file.pdf', 'mime' => 'application/pdf']);
    }
}

In this example, we're creating a MyMail class that has a file property. We're also using the attach method to attach the file to the email.

Step 2: Send the mail

To send the mail, you can use the Mail::send method:

$file = storage_path('app/files/my-file.pdf');
$mail = new MyMail($file);
Mail::send('emails.my-mail', [], function ($message) use ($mail) {
    $message->to('[email protected]')->subject('My Mail');
});

In this example, we're creating a new instance of the MyMail class and passing the file path to the constructor. We're then sending the mail using the Mail::send method, passing the MyMail instance as the first argument.

Step 3: Configure the email template

Create a new file in the resources/views/emails directory, e.g., my-mail.blade.php. In this file, you can add the HTML content for the email:

<!DOCTYPE html>
<html>
<head>
    <title>My Mail</title>
</head>
<body>
    <h1>My Mail</h1>
    <p>This is a test email.</p>
    @if ($file)
        <a href="{{ $file->getUrl() }}">Download file</a>
    @endif
</body>
</html>

In this example, we're using the @if statement to check if the file property is set. If it is, we're displaying a link to download the file.

That's it! When you send the mail, the file will be attached to the email and the recipient will be able to download it.

Note: Make sure to configure your email settings in the config/mail.php file and set the driver to smtp or sendmail depending on your email provider.