Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sent mail middleware #8

Merged
merged 9 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/tobmoeller/laravel-mail-allowlist/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/tobmoeller/laravel-mail-allowlist/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain)
[![Total Downloads](https://img.shields.io/packagist/dt/tobmoeller/laravel-mail-allowlist.svg?style=flat-square)](https://packagist.org/packages/tobmoeller/laravel-mail-allowlist)

This package provides a customizable middleware pipeline for email messages, allowing you to filter, modify, and inspect emails before they are sent.
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:**

Expand All @@ -27,16 +27,18 @@ This package provides a customizable middleware pipeline for email messages, all
- 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 or message bodies in the logs.
- 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` event 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.
> 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

Expand All @@ -52,7 +54,7 @@ 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 just to keep the edited config values.
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
Expand All @@ -77,18 +79,26 @@ MAIL_ALLOWLIST_GLOBAL_TO="[email protected];[email protected]"
MAIL_ALLOWLIST_GLOBAL_CC="[email protected];[email protected]"
MAIL_ALLOWLIST_GLOBAL_BCC="[email protected];[email protected]"

# Configure logging
# 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

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:

```php
'middleware' => [
'pipeline' => [
ToFilter::class;
CcFilter::class;
BccFilter::class;
Expand All @@ -105,7 +115,7 @@ The order of middleware in the pipeline matters. Each middleware can modify the
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:

```php
'middleware' => [
'pipeline' => [
ToFilter::class;
EnsureRecipients::class; // stops further execution when no recipients remain
CcFilter::class;
Expand Down Expand Up @@ -141,14 +151,34 @@ class CancelMessageMiddleware implements MailMiddlewareContract
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.

```php
'middleware' => [
'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

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.

```php
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

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.
Expand All @@ -171,7 +201,7 @@ class CustomLogMessage implements GenerateLogMessageContract
}
```

#### Customizing the log message content
#### Customizing the log creation

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

Expand Down Expand Up @@ -219,6 +249,27 @@ class AppServiceProvider extends ServiceProvider
}
```

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

```php
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

```bash
Expand Down
6 changes: 6 additions & 0 deletions UPGRADE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Upgrade Guide

## Upgrading from 0.4 to 0.5

The `mail-allowlist.php` configuration structure has changed. You should compare and incorporate any of these changes into your existing file if you have previously published it. (It may be easiest to make a backup copy of your existing file, re-publish it from this package, and then re-make your customizations to it.)

Loading