Laravel Email Attachment: A Step-by-Step Guide

Laravel Email Attachment: A Step-by-Step Guide

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 purposes. This tutorial will teach you step-by-step how to send emails with a PDF file in Laravel 8.

1. Create a Laravel Application

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

2. Configure SMTP in the .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