PHPackages                             tobmoeller/laravel-mail-allowlist - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. tobmoeller/laravel-mail-allowlist

Abandoned → [tobmoeller/laravel-mail-middleware](/?search=tobmoeller%2Flaravel-mail-middleware)Library[Validation &amp; Sanitization](/categories/validation)

tobmoeller/laravel-mail-allowlist
=================================

Prevent stray mails from your laravel application

0.6(1y ago)12.5k[2 PRs](https://github.com/TobMoeller/laravel-mail-allowlist/pulls)MITPHPPHP ^8.2CI passing

Since Sep 23Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/TobMoeller/laravel-mail-allowlist)[ Packagist](https://packagist.org/packages/tobmoeller/laravel-mail-allowlist)[ Docs](https://github.com/tobmoeller/laravel-mail-allowlist)[ GitHub Sponsors]()[ RSS](/packages/tobmoeller-laravel-mail-allowlist/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (12)Versions (11)Used By (0)

Prevent stray mails from your Laravel application
=================================================

[](#prevent-stray-mails-from-your-laravel-application)

[![Latest Version on Packagist](https://camo.githubusercontent.com/0fe3cd9968f8af74da73fc287bd86514455b243ce51edc48cd1966c1491cf946/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f626d6f656c6c65722f6c61726176656c2d6d61696c2d616c6c6f776c6973742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tobmoeller/laravel-mail-allowlist)[![GitHub Tests Action Status](https://camo.githubusercontent.com/1308865b4030fff8a8859a4e67ec23eb3ffbd4666f1510bfa711de00cbe345a1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f626d6f656c6c65722f6c61726176656c2d6d61696c2d616c6c6f776c6973742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/tobmoeller/laravel-mail-allowlist/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/20da8d69749269441ba98775fe0c9b5da3be949c36d84cb215d9da49a91d95e9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f626d6f656c6c65722f6c61726176656c2d6d61696c2d616c6c6f776c6973742f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/tobmoeller/laravel-mail-allowlist/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/28c43b8f47e9c8f51b4f68bde41994e8a27ef1cd8e65785d8ecdbbb4a046d7a9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f626d6f656c6c65722f6c61726176656c2d6d61696c2d616c6c6f776c6973742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tobmoeller/laravel-mail-allowlist)

Caution

**Package moved**

The package name has changed to `laravel-mail-middleware` and the repository was moved:

This package provides a customizable middleware pipeline for email messages, allowing you to filter, modify, and inspect emails before they are sent as well as inspecting just sent emails.

**Key Features:**

- **Recipient Allowlist Filtering:**

    - Filter outgoing email recipients based on a configurable allowlist of domains and specific email addresses.
    - Ideal for staging and testing environments to prevent unintended emails from reaching unintended recipients.
    - Automatically removes recipients not matching the allowlist from the "To", "Cc", and "Bcc" fields.
    - If no valid recipients remain after filtering, the email is canceled to prevent unintended delivery.
- **Add Global Recipients:**

    - Set default or global "To", "Cc", and "Bcc" recipients via configuration.
    - Ensure certain recipients always receive emails, such as administrators, audit logs, or monitoring addresses.
- **Customizable Middleware Pipeline:**

    - Utilize a middleware pipeline similar to Laravel's HTTP middleware, but for outgoing emails.
    - Add, remove, or reorder middleware to control the processing of emails.
- **Custom Middleware Support:**

    - Create your own middleware to implement custom logic for outgoing emails.
    - Modify email content, set headers, add attachments, or perform any email transformation needed.
    - Middleware can inspect emails, log information, or integrate with other services.
    - You can define custom middleware that runs before or after an email is sent.
- **Advanced Logging Options:**

    - Configure logging to use custom channels.
    - Set custom log levels (e.g., 'debug', 'info', 'error', etc.).
    - Enable mail middleware to add individual log messages during email processing.
    - Choose whether to include middleware logs, email message headers, message meta data or message bodies in the logs.
    - Write logs for messages that are about to be sent and for messages that have just been sent.

> **Important Note:**
>
> This package utilizes Laravel's `MessageSending` and `MessageSent` events to inspect and modify outgoing emails. If your application has custom listeners or modifications affecting this event, please thoroughly test the package to ensure it integrates seamlessly and maintains the correct filtering functionality.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require tobmoeller/laravel-mail-allowlist
```

You can publish the config file with:

```
php artisan vendor:publish --tag="mail-allowlist-config"
```

Your Laravel application will merge your local config file with the package config file. This enables you to just keep the edited configuration values. Additionally this package provides the ability to configure most of the required values through your environment variables.

Usage
-----

[](#usage)

You can configure the package through environment variables:

```
# Enable the package
MAIL_ALLOWLIST_ENABLED=true

# Enable the mail middleware (allowlist, global recipients)
MAIL_ALLOWLIST_MIDDLEWARE_ENABLED=true

# Define a semicolon separated list of allowed domains
MAIL_ALLOWLIST_ALLOWED_DOMAINS="foo.com;bar.com"

# Define a semicolon separated list of allowed emails
MAIL_ALLOWLIST_ALLOWED_EMAILS="mail@foo.com;mail@bar.com"

# Define a semicolon separated list of globally added emails
MAIL_ALLOWLIST_GLOBAL_TO="mail@foo.com;mail@bar.com"
MAIL_ALLOWLIST_GLOBAL_CC="mail@foo.com;mail@bar.com"
MAIL_ALLOWLIST_GLOBAL_BCC="mail@foo.com;mail@bar.com"

# Configure the logging of emails before they are sent
MAIL_ALLOWLIST_LOG_ENABLED=true
MAIL_ALLOWLIST_LOG_CHANNEL=stack # optional, defaults to Laravel's logging.default
MAIL_ALLOWLIST_LOG_LEVEL=error # optional, defaults to info

# Enable mail middleware that runs after the email is sent
MAIL_ALLOWLIST_SENT_MIDDLEWARE_ENABLED=true

# Configure the logging of emails after they are sent
MAIL_ALLOWLIST_SENT_LOG_ENABLED=true # optional, defaults to sending log
MAIL_ALLOWLIST_SENT_LOG_CHANNEL=stack # optional, defaults to sending log
MAIL_ALLOWLIST_SENT_LOG_LEVEL=info # optional, defaults to sending log
```

### Customizing the Middleware Pipeline

[](#customizing-the-middleware-pipeline)

The package processes outgoing emails through a middleware pipeline, allowing you to customize or extend the email handling logic. By default, the pipeline includes the following middleware:

```
'pipeline' => [
    ToFilter::class;
    CcFilter::class;
    BccFilter::class;
    AddGlobalTo::class,
    AddGlobalCc::class,
    AddGlobalBcc::class,
    EnsureRecipients::class;
],
```

#### Reordering or Removing Middleware

[](#reordering-or-removing-middleware)

The order of middleware in the pipeline matters. Each middleware can modify the email before passing it to the next middleware. You can also reorder or remove middleware from the pipeline to suit your requirements. For example, if you want to disable the `BccFilter` and want the pipeline to stop right after no recipients remain in the `ToFilter`, you can adjust the pipeline:

```
'pipeline' => [
    ToFilter::class;
    EnsureRecipients::class; // stops further execution when no recipients remain
    CcFilter::class;
    // BccFilter::class; // disabled
],
```

#### Creating Custom Middleware

[](#creating-custom-middleware)

You can add your own middleware to the pipeline to modify, inspect, or control outgoing emails according to your application's needs. For example, to prevent a mail from being sent on a custom condition, you might create a middleware like this:

```
use Closure;
use TobMoeller\LaravelMailAllowlist\MailMiddleware\MailMiddlewareContract;
use TobMoeller\LaravelMailAllowlist\MailMiddleware\MessageContext;

class CancelMessageMiddleware implements MailMiddlewareContract
{
    public function handle(MessageContext $messageContext, Closure $next): mixed
    {
        if ($customCondition) {
            // Indicate that the message should be canceled
            $messageContext->cancelSendingMessage('Custom reason');
            // Prevent execution of following middleware
            return null;
        }

        return $next($messageContext);
    }
}
```

Then add it to your middleware pipeline. This can be done as a class-string which will be instantiated by Laravel's service container or as a concrete instance.

```
'pipeline' => [
    // Upstream middleware
    \App\Mail\Middleware\CancelMessageMiddleware::class, // As a class-string.
    new \App\Mail\Middleware\CancelMessageMiddleware(), // As an instance
    // Downstream middleware
],
```

#### Custom Middleware for already sent emails

[](#custom-middleware-for-already-sent-emails)

You can add custom middleware to the sent pipeline to run custom logic on the sent emails like creating database records. The process is similar to the sending middleware but requires you to implement the `MailSentMiddlewareContract` interface in your middleware class.

```
use Closure;
use TobMoeller\LaravelMailAllowlist\MailSentMiddleware\MailSentMiddlewareContract;
use TobMoeller\LaravelMailAllowlist\MailSentMiddleware\SentMessageContext;

class CustomSentMessageMiddleware implements MailSentMiddlewareContract
{
    public function handle(SentMessageContext $messageContext, Closure $next): mixed
    {
        // custom code

        return $next($messageContext);
    }
}
```

### Customizing the Logging Behavior

[](#customizing-the-logging-behavior)

You can control most of the logging behavior from environment variables or the configuration file. For more advanced use cases, you might want to have full control over how log messages are generated and where they are sent. You can achieve this by binding your own implementations of the log content generation action and/or the logging action itself.

#### Customizing the log message content

[](#customizing-the-log-message-content)

Create a new class that implements `GenerateLogMessageContract` to define how log messages are generated:

```
use TobMoeller\LaravelMailAllowlist\Actions\Logs\GenerateLogMessageContract;
use TobMoeller\LaravelMailAllowlist\Facades\LaravelMailAllowlist;
use TobMoeller\LaravelMailAllowlist\MailMiddleware\MessageContext;

class CustomLogMessage implements GenerateLogMessageContract
{
    public function generate(MessageContext $messageContext): string
    {
        // Generate your own log message
    }
}
```

#### Customizing the log creation

[](#customizing-the-log-creation)

Create a new class that implements `LogMessageContract` to define how log messages are handled:

```
use TobMoeller\LaravelMailAllowlist\Actions\Logs\LogMessageContract;
use TobMoeller\LaravelMailAllowlist\Facades\LaravelMailAllowlist;
use TobMoeller\LaravelMailAllowlist\MailMiddleware\MessageContext;

class CustomMessageLogging implements LogMessageContract
{
    /**
     * Optional:
     * Inject the message generator into your class to use the default
     * message generation (is resolved by the service container)
     */
    public function __construct(
        public GenerateLogMessageContract $generateLogMessage
    ) {}

    public function log(MessageContext $messageContext): void
    {
        // Handle logging yourself
    }
}
```

#### Binding Custom Implementations

[](#binding-custom-implementations)

To instruct Laravel to use your custom classes, you need to bind them in your application's service container. This is typically done in a service provider like `App\Providers\AppServiceProvider`.

```
use TobMoeller\LaravelMailAllowlist\Actions\Logs\GenerateLogMessageContract;
use TobMoeller\LaravelMailAllowlist\Actions\Logs\LogMessageContract;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Bind the custom log message generator
        $this->app->bind(GenerateLogMessageContract::class, CustomLogMessage::class);

        // Bind the custom log handler
        $this->app->bind(LogMessageContract::class, CustomMessageLogging::class);
    }
}
```

### Customize the behavior after an email is sent

[](#customize-the-behavior-after-an-email-is-sent)

Customizing the logging for already sent mails is similar to customizing the logging of outgoing mails. You have to bind your custom implementations of the `SentLogMessageContract` and `GenerateSentLogMessageContract` interfaces in a service provider.

```
use TobMoeller\LaravelMailAllowlist\Actions\Logs\GenerateSentLogMessageContract;
use TobMoeller\LaravelMailAllowlist\Actions\Logs\SentLogMessageContract;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Bind the custom log message generator
        $this->app->bind(GenerateSentLogMessageContract::class, CustomSentLogMessage::class);

        // Bind the custom log handler
        $this->app->bind(SentLogMessageContract::class, CustomSentMessageLogging::class);
    }
}
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Tobias Möller](https://github.com/TobMoeller)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance71

Regular maintenance activity

Popularity17

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~31 days

Recently: every ~38 days

Total

6

Last Release

438d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/320371356322fcd6fe7849b4531681eb5278c12c01f189aea4a481e89d7b8c01?d=identicon)[TobiasMoeller](/maintainers/TobiasMoeller)

---

Top Contributors

[![TobMoeller](https://avatars.githubusercontent.com/u/63605405?v=4)](https://github.com/TobMoeller "TobMoeller (18 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (7 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (5 commits)")

---

Tags

laravelTobias Möllerlaravel-mail-allowlist

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/tobmoeller-laravel-mail-allowlist/health.svg)

```
[![Health](https://phpackages.com/badges/tobmoeller-laravel-mail-allowlist/health.svg)](https://phpackages.com/packages/tobmoeller-laravel-mail-allowlist)
```

###  Alternatives

[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[axlon/laravel-postal-code-validation

Worldwide postal code validation for Laravel and Lumen

3853.3M1](/packages/axlon-laravel-postal-code-validation)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[ziming/laravel-zxcvbn

Zxcvbn Password validation rule for Laravel

3056.7k](/packages/ziming-laravel-zxcvbn)[laravel-validation-rules/phone

Validate that a phone number is in the correct format

69355.5k](/packages/laravel-validation-rules-phone)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
