Skip to main content

[Laravel] Tạo file PDF và gửi email với Laravel

Đây là hướng dẫn tạo file pdf nhanh chóng cùng Laravel với dompdf. Sau đó là gửi email đến người dùng.

Bước 1 - Cài đặt Laravel và dompdf

Dùng lệnh dưới đây

# tạo project
composer create-project --prefer-dist laravel/laravel blog
# cài đặt package
composer require barryvdh/laravel-dompdf

Bước 2 - Cấu hình SMTP Email trong Laravel

Dưới đây là config mẫu đang sử dụng smtp Gmail trong hệ thống sent mail của Laravel

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=example@gmail.com
MAIL_PASSWORD=passwordEmail
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=example@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Bước 3 - Tạo Route để xử lý file pdf và gửi email

Trong file routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PDFController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('send-email-pdf', [PDFController::class, 'index']);

Bước 4 - Khởi tạo Controller để tạo file PDF

Tạo controller app/Http/Controllers/PDFController.php với nội dung như sau:

<?php
     
namespace App\Http\Controllers;
      
use Illuminate\Http\Request;
use App\Mail\MailExample;
use PDF;
use Mail;
   
class PDFController extends Controller
{
      
   /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Http\Response
    */
   public function index()
   {
       $data["email"] = "email_nhan@gmail.com";
       $data["title"] = "From example.com";
       $data["body"] = "This is Demo";
   
       $pdf = PDF::loadView('emails.myTestMail', $data);
       $data["pdf"] = $pdf;
 
       Mail::to($data["email"])->send(new MailExample($data));
   
       dd('Mail sent successfully');
   }
      
}

 

Bước 5 - Tạo Class Mail để gửi email

Dùng lệnh sau:

php artisan make:mail MailExample

Bạn sẽ thấy xuất hiện folder Mail và trong đó chứa file MailExample.php, thêm đoạn snippet code bên dưới

<?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 MailExample extends Mailable
{
    use Queueable, SerializesModels;
  
    public $mailData;
  
    /**
     * Create a new message instance.
     */
    public function __construct($mailData)
    {
        $this->mailData = $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.myTestMail',
            with: $this->mailData
        );
    }
  
    /**
     * Get the attachments for the message.
     *
     * @return array

     */
    public function attachments(): array
    {
        return [
            Attachment::fromData(fn () => $this->mailData['pdf']->output(), 'Report.pdf')
                ->withMime('application/pdf'),
        ];
    }
}

Bước 6 - Tạo View của nội dung file PDF

Tạo một view resources/views/emails/myTestMail.blade.php chứa nội dung PDF như sau

<!DOCTYPE html>
<html>
<head>
   <title>example.com</title>
</head>
<body>
   <h1>{{ $title }}</h1>
   <p>{{ $body }}</p>
    
   <p>Thank you</p>
</body>
</html>

Bước 7 - Test

Dùng lệnh php artisan serve để khởi động dự án Laravel, sau đó truy cập vào đường dẫn

http://localhost:8000/send-email-pdf

Giờ vào email của bạn để kiểm tra email 

Nguồn: itsolutionstuff.com