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
Datatables Expand/Collapse Columns
Datatables Expand/Collapse Col...

In this article, we will see how to expand/collapse columns in datatable. The Datatables API has a number of method...

Read More

Jun-05-2022

Implementing CQRS (Command Query Responsibility Segregation) in Laravel 11
Implementing CQRS (Command Que...

Hello, laravel web developers! In this guide, I'll show you how to implement CQRS (Command Query Responsibility Segr...

Read More

Sep-30-2024

How To Create Custom Login Page In Django
How To Create Custom Login Pag...

In this article, we will see how to create a custom login page in django. how to allow user registration, login, an...

Read More

May-14-2022

Laravel 8 Has Many Through Relationship Example
Laravel 8 Has Many Through Rel...

In this example we will see laravel 8 has many through relationship example. hasManyThrough relationship difficult to un...

Read More

Nov-17-2021