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

Laravel Export & Import CSV

Laravel Export & Import CSV

Trong bài viết này, tôi sẽ hướng dẫn các tạo cách Export hoặc Import CSV trong Laravel. Nhưng thay vì chỉ viết hàm đơn thuần trong PHP thì tôi sẽ hướng dẫn các tạo ra một Service trong Laravel bằng cá...

Laravel Socialite Login With Facebook

Laravel Socialite Login With Facebook

Ngoài xác thực dựa trên biểu mẫu điển hình, Laravel cũng cung cấp một cách đơn giản và thuận tiện để sử dụng Laravel Socialite để xác thực với các nhà cung cấp OAuth. Socialite hiện hỗ trợ xác thực qu...

Laravel Task Scheduling

Laravel Task Scheduling

Trong các ứng dụng lớn, bạn cần lên lịch định kì cho các công việc bằng Cron jobs.  Tại số một số thời điểm, việc quản lý các cron jobs trở nên cồng kềnh và khó khăn hơn. Laravel Scheduler là một côn...

Implementing Private User Folders with CKFinder in Laravel

Implementing Private User Folders with CKFinder in Laravel

CKFinder 3 CKFinder 3 là trình quản lý tập tin được tích hợp với CKEditor 4 và CKEditor 5. Nó giúp bạn dễ dàng đưa các tập tin và hình ảnh vào nội dung của Editor một cách an toàn. Đây là một tín...

Laravel One to Many Eloquent Relationship

Laravel One to Many Eloquent Relationship

One to Many Relationship được sử dụng trong trường hợp một dữ liệu của một bảng được liên kết với một hoặc nhiều dữ liệu ở bảng khác. Ví dụ, một bài post có thể có nhiều comment. Vì vậy, trong hướn...

Laravel Logging Of Database Queries

Laravel Logging Of Database Queries

Laravel là một Framework PHP mạnh mẽ và linh hoạt, giúp cho việc phát triển ứng dụng trở nên đơn giản và dễ dàng hơn. Một trong những tính năng hữu ích của Laravel là khả năng ghi nhật ký truy vấn...

Laravel 9 REST API With Sanctum Authentication

Laravel 9 REST API With Sanctum Authentication

Laravel Sanctum Laravel Sanctum cung cấp một hệ thống authentication đơn giản cho các SPA, ứng dụng Mobile và API đơn giản sử dụng token. Sanctum cho phép ứng dụng của bạn phát hành các mã token...

Laravel One to One Eloquent Relationship

Laravel One to One Eloquent Relationship

Mối quan hệ một-một là một mối quan hệ rất cơ bản. Trong hướng dẫn này, tôi sẽ hướng dẫn bạn cách tạo dữ liệu và truy xuất dữ liệu bằng Eloquent Model. Trong hướng dẫn này, tôi sẽ tạo hai bảng là u...

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...

ManhDanBlogs