Laravel 11 Send Email with Attachment

Websolutionstuff | Sep-06-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to send emails with attachments in laravel 11. In laravel 11, we'll send mail with a PDF file and image as attachments. In this guide, we'll explore how to attach various file types—such as images, PDFs, CSVs, ZIPs, and more—to emails.

To add attachments, you'll include them in the array returned by the message's attachments method. While I'll be using Mailtrap for testing, you can use Gmail, Mailtrap, or any other email service that fits your needs.

Laravel 11 Send Email with Attachment

Laravel 11 Send Email with Attachment

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-example

 

Step 2: Make Configuration

Next, we'll define the email configuration into a .env file

.env

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

 

Step 3: Create Mail Class

Then, we'll create a mail class called TestMail for sending emails with attachments.

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;

    /**
     * Create a new message instance.
     */
    public function __construct(public $mailData)
    {
        // 
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->mailData['title'],
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.testMail',
            with: $this->mailData
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array
     */
    public function attachments(): array
    {
        $attachments = [];

        if(!empty($this->mailData['files'])){
            foreach ($this->mailData['files'] as $key => $file) {
                $attachments[] = Attachment::fromPath($file);
            }
        }

        return $attachments;
    }
}

 

Step 4: Create Controller

Next, we'll create a controller using the following command.

php artisan make:controller MailController

app/Http/Controllers/MailController.php

<?php

namespace App\Http\Controllers;

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

class MailController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $mailData = [
            'title' => 'Mail from Techsolutionstuff',
            'body' => 'This is for testing email using SMTP.',
            'files' => [
                public_path('attachments/test-pdf.pdf'),
                public_path('attachments/test-img.png')
            ]
        ];
        
        $email = '[email protected]';
        Mail::to($email)->send(new TestMail($mailData));
           
        dd("Email is sent successfully.");
    }
}

 

Step 5: Define Routes

Now, define the routes into the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\MailController;
    
Route::get('send-mail', [MailController::class, 'index']);

 

Step 6: Create Blade View

Then, we'll create a blade file and add the following HTML code to that file.

resources/views/emails/testMail.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Send Email with Attachment - Techsolutionstuff</title>
</head>
<body>
    <h1>{{ $mailData['title'] }}</h1>
    <p>{{ $mailData['body'] }}</p>
  
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
     
    <p>Thank you</p>
</body>
</html>

 

Step 7: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
Multi Step Form Example In Laravel
Multi Step Form Example In Lar...

Today in this post we will see multi step form example in laravel, here we will create laravel multi step form example.&...

Read More

Jul-21-2021

How To Integrate Email Template Builder In Laravel
How To Integrate Email Templat...

In this article, we will see how to integrate an email template builder in laravel. Also, you can integrate an emai...

Read More

Feb-22-2023

How To Add Action Button In Angular 15 Material Datepicker
How To Add Action Button In An...

In this tutorial, I will guide you through the process of adding an action button to the Angular 15 Material datepicker...

Read More

Jul-07-2023

How To Check Array Is Empty Or Null In Javascript
How To Check Array Is Empty Or...

In this example, I will show you how to check if an array is empty or null in javascript or jquery. When we are wor...

Read More

Aug-18-2020