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
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=92js46368372
MAIL_PASSWORD=3938sdish
MAIL_ENCRYPTION=tls
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>
<html>
<head>
<title>Laravel 8 Send Email Example</title>
</head>
<body>
<h1>This is test mail from Tutsmake.com</h1>
<p>Laravel 8 send email example</p>
</body>
</html>
6. Email Sending Controller File
<?php
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;
$data["client_name"]=$request->client_name;
$data["subject"]=$request->subject;
$pdf = PDF::loadView('send-email', $data);
try{
Mail::send('mails.mail', $data, function($message)use($data,$pdf) {
$message->to($data["email"], $data["client_name"])
->subject($data["subject"])
->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";
}else{
$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:
http://127.0.0.1:8000/send-email-with-pdf
Subscribe to the Email Newsletter