Laravel 9 Send Email With PDF Attachment

In this article, we will see laravel 9 send an email with a pdf attachment. As we all know mail functionalities are common in all projects but if you want to send a mail with an attachment in some cases then this post is for you here we will see how to attach the pdf file in an email in laravel 9.

Also, you can send any attachment format or files like a png file, excel file, CSV file, and much more and for sending mail we will use mailtrap for testing purposes. So, you use it as per the requirement.

So, let's see how to send an email with a pdf attachment in laravel 9, send a pdf attachment in mail laravel 9 and laravel 9 send an email with an attachment.

How To Send Email With PDF Attachment In Laravel 9

Step 1: Install Laravel 9

Step 2: Set Configuration for Send Email

Step 3: Add Route

Step 4: Add Controller

Step 5: Create Blade File

Step 6: Run Laravel 9 Application

 

Step 1: Install Laravel 9

In this step, we will install the laravel 9 application using the following command.

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

 

 

Step 2: Set Configuration for Send Email

Now, we will add email configuration with mail driver, mail host, mail port, mail username, mail password, etc in .env file

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, add a route in the web.php file.

routes/web.php

Route::get('send/mail', [SendMailController::class, 'send_mail'])->name('send_mail');

 

Step 4: Add Controller

In this step, we will create SendMailController and add the below code in the controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;

class SendMailController extends Controller
{
    public function send_mail(Request $request)
    {
        $data["email"] = "test@gmail.com";
        $data["title"] = "Techsolutionstuff";
        $data["body"] = "This is test mail with pdf 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);
            }            
        });

        echo "Mail send successfully !!";
    }
}

 

 

Step 5: Create Blade File

Now, create a blade file in resources\views\mail\Test_mail.blade.php to display messages in the mail.

Hi, Techsolutionstuff <br/>
This is Test Mail.<br />
Thank you...!!

 

Step 6: Run Laravel 9 Application

Now, run this laravel 9 send an email with a pdf attachment application using the artisan command.

php artisan serve

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS