How to send email with attachment in Laravel

How to send email with attachment in Laravel

This tutorial will show you how to send an email with a pdf attachment in the laravel 8 Application.

We will mailtrap for sending emails for testing purpose. This tutorial will teach you to step by step how to send emails with a pdf file in laravel 8.

1. Create Laravel Application

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


2. Configure SMTP in .env file


3. Install PDF Package

composer require carlos-meneses/laravel-mpdf


4. Email Sending Route

use App\Http\Controllers\SendEmailController;

Route::get('send-email-with-pdf', [SendEmailController::class, 'index']);


5. Email Sending Blade File

<!DOCTYPE html>
 <title>Laravel 8 Send Email Example</title>
 <h1>This is test mail from</h1>
 <p>Laravel 8 send email example</p>


6. Email Sending Controller File


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use PDF;
class SendEmailController extends Controller
    public function sendMail(Request $request){
        $data["email"] = $request->email;
        $pdf = PDF::loadView('send-email', $data);
            Mail::send('mails.mail', $data, function($message)use($data,$pdf) {
            $message->to($data["email"], $data["client_name"])
            ->attachData($pdf->output(), "invoice.pdf");
        }catch(\Exception $exception){
            $this->serverstatuscode = "0";
            $this->serverstatusdes = $exception->getMessage();
        if (Mail::failures()) {
             $this->statusdesc  =   "Error sending mail";
             $this->statuscode  =   "0";
           $this->statusdesc  =   "Message sent Succesfully";
           $this->statuscode  =   "1";
        return response()->json(compact('this'));


7. Run Development Project


In this step, use this PHP artisan serve command to start your server locally:

php artisan serve

Then open a browser and fire the following URL on it:

Get The latest Coding solutions.

Subscribe to the Email Newsletter