Laravel 11 Send Email with Attachment Example

Hello developers! In this guide, we'll explore how to send emails with attachments in Laravel 11. We'll learn how to attach various file types such as images, PDFs, CSVs, ZIPs, and more. Let's dive in and enhance our email capabilities.

To add attachments to an email, you will add attachments to the array returned by the message's attachments method. Here, I'll use Mailtrap for testing purposes but you can use mailtrap, Gmail, or as per your convenience.

Laravel 11 Send Email with Attachment

 

Step 1: Install Laravel 11

We will install the laravel 11 application using the following command.

composer create-project --prefer-dist laravel/laravel laravel_11_example

 

 

Step 2: Setup Mail Configuration

Next, we'll add email configuration details including the mail driver, mail host, mail port, mail username, mail password, etc., in the .env file. Let's ensure our email setup is properly configured.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_user_name
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=TLS

 

Step 3: Add Route

Now, let's add a route in the web.php file to handle our email functionality.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SendMailController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('send/mail', [SendMailController::class, 'sendMailWithAttachment']);

 

Step 4: Add Controller

In this step, we'll create the SendMailController and add the following code to it.

app/Http/Controllers/SendMailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Mail\TestMail;
use Mail;

class SendMailController extends Controller
{
    public function sendMailWithAttachment(Request $request)
    {
        // Laravel 8
        // $data["email"] = "test@gmail.com";
        // $data["title"] = "Techsolutionstuff";
        // $data["body"] = "This is test mail with attachment";
 
        // $files = [
        //     public_path('attachments/test_image.jpeg'),
        //     public_path('attachments/test_pdf.pdf'),
        // ];
  
        // Mail::send('mail.test_mail', $data, function($message)use($data, $files) {
        //     $message->to($data["email"])
        //             ->subject($data["title"]);
 
        //     foreach ($files as $file){
        //         $message->attach($file);
        //     }            
        // });

        $mailData = [
            'title' => 'This is Test Mail',
            'files' => [
                public_path('attachments/test_image.jpeg'),
                public_path('attachments/test_pdf.pdf'),
            ];
        ];
           
        Mail::to('to@gmail.com')->send(new TestMail($mailData));
             
        echo "Mail send successfully !!";
    }
}

 

Step 5: Create Mail Class

Now, I'll create a mail class using the artisan command. 

php artisan make:mail TestMail

app/Mail/TestMail.php

<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Attachment;
  

class TestMail extends Mailable
{
    use Queueable, SerializesModels;

    public $mailData;

    /**
     * Create a new message instance.
     */
    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }
  
    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Test Mail',
        );
    }
  
    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.testMail'
        );
    }
  
    /**
     * Get the attachments for the message.
     *
     * @return array
     */
    public function attachments(): array
    {
        return [
             Attachment::fromPath('/path/to/file'),
        ];

    }
}

When attaching files to a message, you may also specify the display name and / or MIME type for the attachment using the as and withMime methods.

use Illuminate\Mail\Mailables\Attachment;

/**
 * Get the attachments for the message.
 *
 * @return array<int, \Illuminate\Mail\Mailables\Attachment>
 */
public function attachments(): array
{
    return [
        Attachment::fromPath('/path/to/file')
                ->as('name.pdf')
                ->withMime('application/pdf'),
    ];
}

If you have stored a file on one of your filesystem disks, you can attach it to the email using the fromStorage attachment method.

/**
 * Get the attachments for the message.
 *
 * @return array<int, \Illuminate\Mail\Mailables\Attachment>
 */
public function attachments(): array
{
    return [
        Attachment::fromStorage('/path/to/file'),
    ];
}

 

 

Step 6: Create Blade File

Now, we will create a testMail.blade.php file.

resources\views\mail\testMail.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Send Email with Attachment Example - Techsolutiontuff</title>
</head>
<body>
    <h1>{{ $mailData['title'] }}</h1>
  
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua.</p>
     
    <p>Thank you</p>
</body>
</html>

 

Step 7: Run the Laravel 11 Application

To run the Laravel 11 application for sending emails with attachments, use the artisan command provided below

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS