How to Send Email with File Attachment in Laravel 12?

How to Send Email with File Attachment in Laravel 12

Email communication is an essential feature for modern web applications. Whether it’s sending invoices, reports, resumes, or any type of document, the ability to send emails with file attachments in Laravel adds a lot of flexibility.

Laravel Development Services

Laravel, being a powerful PHP framework, provides a clean and straightforward way to send emails using its built-in Mail functionality. In this tutorial, we will walk you through the process of sending an email with a file attachment in Laravel 12. You’ll learn how to attach files like images, PDFs, CSVs, and ZIPs using the Laravel Mailable class. Let’s get started 

Steps for Laravel 12 Send Mail with Attachments Example

Step 1: Install Laravel 12

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Make Configuration

In the second step, you have to add the mail configuration. Set the mail driver as “gmail” or whatever you choose as driver, the mail host, mail port, mail username, and mail password. Laravel 12 will use these sender details for emails. You can simply add them as follows:

.env

MAIL_MAILER=smtp 
MAIL_HOST=smtp.gmail.com 
MAIL_PORT=465 
MAIL_USERNAME= YOUR EMIAL
MAIL_PASSWORD= YOURPASSWORD
MAIL_ENCRYPTION=tls 
MAIL_FROM_ADDRESS=mygoogle@gmail.com 
MAIL_FROM_NAME="${APP_NAME}"

Step 3: Create Mail Class

In this step, we will create a mail class called `DemoMail` for sending emails with attachment. Here, we will write code for which view will be called and the object of the user. So let’s run the below command.

php artisan make:mail DemoMail

Now, let’s update the code in the `DemoMail.php` file as follows:

app/Mail/DemoMail.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 DemoMail 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.demoMail',
            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

In this step, we will create a `MailController` with an `index()` method where we will write code to send an email to a given email address. So first, let’s create the controller by executing the following command and update the code in it:

php artisan make:controller MailController

Now, update the code in the MailController file.

app/Http/Controllers/MailController.php

<?php

namespace App\Http\Controllers;

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

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

Step 5: Create Routes

In this step, we need to create routes for a list of sending emails. So, open your “routes/web.php” file and add the following route.

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

In this step, we will create a blade view file and write the email that we want to send. Now we are going to enter some random text. Create the following files in the “emails” folder.

resources/views/emails/demoMail.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>magecomp.com</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 Laravel App

Once you have completed the above steps, you need to execute the following command and hit enter to run your Laravel app:

php artisan serve

Then, go to your web browser, type the URL provided below, and look at the app’s output:

http://localhost:8000/send-mail 

Conclusion:

It is easy to send emails with attachments using Laravel 12 with the built-in Mail class. By only performing a couple of simple steps: configuring a mailer, creating a Mailable and attaching a document, Laravel can send professional emails with documents, invoices, and reports.

If you are building an application that sends emails to customers, for order confirmations or file sharing, you can do it all efficiently and simply with Laravel.

Hire laravel Developer

FAQ

  1. What is Laravel?

Laravel is a web application framework with an elegant and expressive syntax that provides a foundation and starting point for creating web applications in PHP.

  1. Why Choose Laravel?

Laravel has a robust set of features, including an expressive database abstraction layer (Eloquent), a powerful templating engine (Blade), built-in authentication and authorization, an expressive routing system, queues, scheduled tasks, and a command line tool (Artisan CLI). One of the biggest focuses of Laravel is the developer experience, and it has tons of powerful tools to help with that experience.

Previous Article

HTTP 401 Unauthorized Response Error: What it is & How to Fix it?

Next Article

HTTP 403 Forbidden Error: What Is It & How To Fix It?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨