Trong quá trình phát triển web, việc gửi email là một chức năng quan trọng để thông báo, đặt lại mật khẩu, hoặc tương tác với người dùng.

Tuy nhiên, khi chúng ta đang trong quá trình phát triển, việc thử nghiệm và gỡ lỗi chức năng gửi email lại càng trở nên quan trọng hơn. Trong những trường hợp như vậy, chúng ta thường muốn tránh gửi email thực sự đến người dùng thực tế.

Laravel cung cấp một sự kiện có tên là  MessageSending cho phép chúng ta điều chỉnh hành vi gửi email.

Dựa trên sự kiện này, chúng ta sẽ tạo một  Listener có tên là MessageSendingRedirector để điều hướng tất cả các email được gửi, đảm bảo rằng trong quá trình phát triển hoặc gỡ lỗi, tất cả các thông điệp email sẽ được chuyển đến địa chỉ email của đội ngũ nhà phát triển.

Tính năng này rất hữu ích khi làm việc với database của môi trường thực, nơi nhà phát triển muốn ngăn chặn email thử nghiệm đến người dùng thực tế.

Cấu hình Mail Sending Redirector

Bạn thêm các config bên dưới vào config/mail.php:

/*
|--------------------------------------------------------------------------
| Email Redirection Settings
|--------------------------------------------------------------------------
|
| Configure the redirection settings for outgoing emails. These settings
| control whether the email redirection feature is enabled, and specify
| the recipients, reply-to address, and error-to address for redirection.
|
| 'enabled': Indicates whether the email redirection feature is active.
|
| 'to': Default recipient for redirected emails.
|
| 'cc': Default carbon copy (CC) recipient for redirected emails.
|
| 'bcc': Default blind carbon copy (BCC) recipient for redirected emails.
|
| 'reply_to': Default reply-to address for redirected emails.
|
| 'error_to': Default error-to address for redirection error notifications.
|
|--------------------------------------------------------------------------
*/
'redirect' => [
    'enabled' => env('REDIRECT_MAIL_ENABLED', true),
    'to' => env('REDIRECT_MAIL_TO', '[email protected]'),
    'cc' => env('REDIRECT_MAIL_CC', '[email protected]'),
    'bcc' => env('REDIRECT_MAIL_BCC', '[email protected]'),
    'reply_to' => env('REDIRECT_MAIL_REPLY_TO', '[email protected]'),
    'error_to' => env('REDIRECT_MAIL_ERROR_TO', '[email protected]'),
],

 Listener MessageSendingRedirector

Để tạo listener MessageSendingRedirector, bạn cần sử dụng lệnh sau:

php artisan make:listener MessageSendingRedirector

Sau đó, bạn hãy chỉnh sửa app/Listeners/MessageSendingRedirector.php với nội dung như sau:

<?php

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSending;

class MessageSendingRedirector
{
    /**
     * Handle the event.
     *
     * @param  MessageSending  $event
     * @return void
     */
    public function handle(MessageSending $event)
    {
        // Check if the email sending redirection feature is enabled
        if (!$this->getConfigValue('enabled')) {
            return; // If not, exit the function
        }

        // Set recipients for email sending redirection
        $this->setRecipients($event);

        // Set the Reply-To address for email sending redirection
        $this->setReplyTo($event);

        // Set the Errors-To header for email sending redirection
        $this->setErrorTo($event);
    }

    /**
     * Set the recipients for redirection.
     *
     * @param  MessageSending  $event
     * @return void
     */
    protected function setRecipients(MessageSending $event)
    {
        if ($event->message->getTo()) {
            $event->message->setTo($this->getConfigValue('to'));
        }

        if ($event->message->getCc()) {
            $event->message->setCc($this->getConfigValue('cc'));
        }

        if ($event->message->getBcc()) {
            $event->message->setBCc($this->getConfigValue('bcc'));
        }
    }

    /**
     * Set the Reply-To address for redirection.
     *
     * @param  MessageSending  $event
     * @return void
     */
    protected function setReplyTo(MessageSending $event)
    {
        if ($event->message->getReplyTo()) {
            $event->message->setReplyTo($this->getConfigValue('reply_to'));
        }
    }

    /**
     * Set the Errors-To header for redirection.
     *
     * @param  MessageSending  $event
     * @return void
     */
    protected function setErrorTo(MessageSending $event)
    {
        if ($event->message->getHeaders()->get('Errors-To')) {
            $event->message->getHeaders()->get('Errors-To')->setValue($this->getConfigValue('error_to'));
        }
    }

    /**
     * Get configuration value and split it using '|' delimiter.
     *
     * @param  string  $key
     * @return array
     */
    protected function getConfigValue($key)
    {
        return explode('|', config("mail.redirect.$key"));
    }
}

Chúng ta sẽ đăng ký MessageSendingRedirector để lắng nghe sự kiện MessageSending. Sự kiện này sẽ được kích hoạt khi một email được gửi.

Bạn hãy chỉnh sửa /app/Providers/EventServiceProvider.php với nội dung như sau:

<?php

namespace App\Providers;

...
use Illuminate\Mail\Events\MessageSending;
use App\Listeners\MessageSendingRedirector;


class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        ...
        MessageSending::class => [
            MessageSendingRedirector::class,
        ],
    ];
    ...
}

Cách sử dụng Mail Sending Redirector

Để sử dụng Mail Sending Redirector, bạn cần cấu hình các giá trị sau trong .env  của bạn:

REDIRECT_MAIL_ENABLED=true
REDIRECT_MAIL_TO="[email protected]"
REDIRECT_MAIL_CC="[email protected]"
REDIRECT_MAIL_BCC="[email protected]"
REDIRECT_MAIL_REPLY_TO="[email protected]"
REDIRECT_MAIL_ERROR_TO="[email protected]"

Nếu bạn muốn cấu hình chuyển hướng đến nhiều địa chỉ email khác nhau, bạn có thể sử dụng ký tự "|" để phân tách chúng như sau:

REDIRECT_MAIL_ENABLED=true
REDIRECT_MAIL_TO="[email protected]|[email protected]"
REDIRECT_MAIL_CC="[email protected]|[email protected]"
REDIRECT_MAIL_BCC="[email protected]|[email protected]"
REDIRECT_MAIL_REPLY_TO="[email protected]|[email protected]"
REDIRECT_MAIL_ERROR_TO="[email protected]|[email protected]"

CÓ THỂ BẠN QUAN TÂM

Method WhereAny / WhereAll  in Laravel Eloquent

Method WhereAny / WhereAll in Laravel Eloquent

New Laravel 10: Eloquent WhereAny() và WhereAll() Laravel cung cấp cho chúng ta khả năng xây dựng các truy vấn dữ liệu mạnh mẽ với Eloquent ORM, giúp chúng ta có thể xử lý các truy vấn cơ sở dữ li...

Laravel Authentication With Laravel UI

Laravel Authentication With Laravel UI

Laravel UI Laravel UI cung cấp một cách nhanh chóng để mở rộng các route và view cần thiết cho chức năng Authentication và bao gồm các cài đặt liên quan cho Bootstrap, React hoặc Vue. Mặc dù nó v...

Pipeline Design Pattern in Laravel

Pipeline Design Pattern in Laravel

Pipeline Design Pattern là nơi mà các dữ liệu được chuyển qua một chuỗi các nhiệm vụ hoặc giai đoạn. Pipeline hoạt động giống như một chuỗi dây chuyền lắp ráp, nơi dữ liệu được xử lý và sau đó, sẽ...

Laravel Socialite Login With Google

Laravel Socialite Login With Google

Google Google là một công cụ tìm kiếm trên internet. Nó sử dụng một thuật toán độc quyền được thiết kế để truy xuất và sắp xếp các kết quả tìm kiếm nhằm cung cấp các nguồn dữ liệu đáng tin cậy và ph...

Implementing Private User Folders with elFinder in Laravel

Implementing Private User Folders with elFinder in Laravel

elFinder elFinder là một trình quản lý tập tin mã nguồn mở dành cho web, được viết bằng JavaScript sử dụng jQuery UI. elFinder được phát triển dựa trên cảm hứng từ sự tiện lợi và đơn giản của chư...

Simplify Your Laravel Workflow with Laravel Pint

Simplify Your Laravel Workflow with Laravel Pint

Laravel Pint là gì? Laravel Pint là một công cụ sửa đổi mã nguồn của bạn để mã nguồn của bạn tuân thủ theo các tiêu chuẩn. Nói một cách khác, Laravel Pint sẽ quét toàn bộ mã nguồn của bạn, phát...

Laravel View

Laravel View

View là gì? Đây là phần giao diện (theme) dành cho người sử dụng. Nơi mà người dùng có thể lấy được thông tin dữ liệu của MVC thông qua các thao tác truy vấn như tìm kiếm hoặc sử dụng thông qua các...

Laravel Model

Laravel Model

Model là gì? Trong mô hình MVC, chữ “M” viết tắt là Model, Model dùng để xử lý logic nghiệp vụ trong bất kì ứng dụng dựa trên mô hình MVC. Trong Laravel, Model là lớp đại diện cho cấu trúc logic và...

Laravel  Scout Full Text Search with Algolia

Laravel Scout Full Text Search with Algolia

Laravel Scout cung cấp một giải pháp đơn giản, dựa trên trình điều khiển để thêm tìm kiếm Full Text vào các mô hình Eloquent của bạn. Khi sử dụng Eloquent, Scout sẽ tự động giữ chỉ mục tìm kiếm của bạ...

ManhDanBlogs