├── .github └── workflows │ ├── phpstan.yml │ ├── pint.yml │ └── run-tests.yml ├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── config └── mailviewer.php ├── database └── migrations │ └── create_mail_viewer_items_table.php.stub ├── docs ├── screenshot-analytics.png └── screenshot-default.png ├── phpstan.neon.dist ├── phpunit.xml ├── resources └── views │ ├── analytics.blade.php │ └── index.blade.php ├── routes └── web.php ├── src ├── Http │ └── Controllers │ │ └── MailViewerController.php ├── Listeners │ └── CreateMailViewerItem.php ├── MailViewerServiceProvider.php ├── Models │ └── MailViewerItem.php ├── Providers │ └── EventServiceProvider.php └── Subscribers │ └── MessageSentSubscriber.php └── tests ├── Config └── ConfigTest.php ├── Database └── Factories │ └── MailViewerItemFactory.php ├── Events ├── ListensOnMailEventsTest.php └── Notifications │ └── TestNotification.php ├── Models └── MailViewerItemTest.php ├── TestCase.php └── Views └── ViewTest.php /.github/workflows/phpstan.yml: -------------------------------------------------------------------------------- 1 | name: Run PHPStan 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | phpstan: 11 | name: phpstan 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Setup PHP 17 | uses: shivammathur/setup-php@v2 18 | with: 19 | php-version: '8.2' 20 | coverage: none 21 | 22 | - name: Install composer dependencies 23 | uses: ramsey/composer-install@v2 24 | 25 | - name: Run PHPStan 26 | run: ./vendor/bin/phpstan --error-format=github 27 | -------------------------------------------------------------------------------- /.github/workflows/pint.yml: -------------------------------------------------------------------------------- 1 | name: Run Pint 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | pint: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v4 16 | with: 17 | ref: ${{ github.head_ref }} 18 | 19 | - name: Run Pint 20 | uses: aglipanci/laravel-pint-action@2.3.0 21 | 22 | - name: Commit changes 23 | uses: stefanzweifel/git-auto-commit-action@v5 24 | with: 25 | commit_message: Fix styling 26 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | fail-fast: false 14 | matrix: 15 | include: 16 | - php: 8.2 17 | laravel: '11.*' 18 | testbench: '9.*' 19 | dependency-version: prefer-stable 20 | os: ubuntu-latest 21 | - php: 8.2 22 | laravel: '12.*' 23 | testbench: '10.*' 24 | dependency-version: prefer-stable 25 | os: ubuntu-latest 26 | 27 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} 28 | 29 | steps: 30 | - name: Checkout code 31 | uses: actions/checkout@v4 32 | 33 | - name: Cache dependencies 34 | uses: actions/cache@v4 35 | with: 36 | path: ~/.composer/cache/files 37 | key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} 38 | 39 | - name: Setup PHP 40 | uses: shivammathur/setup-php@v2 41 | with: 42 | php-version: ${{ matrix.php }} 43 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 44 | coverage: none 45 | 46 | - name: Install dependencies 47 | run: | 48 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 49 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 50 | 51 | - name: Execute tests 52 | run: vendor/bin/phpunit 53 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor 2 | composer.phar 3 | composer.lock 4 | .php_cs.cache 5 | .DS_Store 6 | /.idea 7 | /.vscode 8 | .phpunit.result.cache 9 | .php-cs-fixer.cache -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Label84 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | 9 | [MIT License](https://opensource.org/licenses/MIT) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel MailViewer 2 | 3 | [![Latest Stable Version](https://poser.pugx.org/label84/laravel-mailviewer/v/stable?style=flat-square)](https://packagist.org/packages/label84/laravel-mailviewer) 4 | [![MIT Licensed](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) 5 | [![Total Downloads](https://img.shields.io/packagist/dt/label84/laravel-mailviewer.svg?style=flat-square)](https://packagist.org/packages/label84/laravel-mailviewer) 6 | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/label84/laravel-mailviewer/run-tests.yml?branch=master&style=flat-square) 7 | 8 | Mailviewer enables you to view and filter mail that is sent by your Laravel application in the browser. The Analytics page gives you insight in the amount of mails sent sent by your application grouped by Notification. 9 | 10 | ![MailViewer screenshot](./docs/screenshot-default.png?raw=true "MailViewer Screenshot") 11 | 12 | - [Laravel Support](#laravel-support) 13 | - [Installation](#installation) 14 | - [Usage](#usage) 15 | - [Filters](#filters) 16 | - [Analytics](#analytics) 17 | - [Examples](#examples) 18 | - [Exclusion list](#exclusion-list) 19 | - [Tests](#tests) 20 | - [License](#license) 21 | 22 | ## Laravel Support 23 | 24 | | Version | Release | 25 | |---------|---------| 26 | | 12.x | ^3.0 | 27 | | 11.x | ^3.0 | 28 | 29 | ## Limitations 30 | 31 | This package tracks mails sent via Laravel's `Mailables` and `Notifications`. 32 | 33 | ## Installation 34 | 35 | ### 1. Require package 36 | 37 | ```sh 38 | composer require label84/laravel-mailviewer 39 | ``` 40 | 41 | ### 2. Publish the config file and migration 42 | 43 | ```sh 44 | php artisan vendor:publish --provider="Label84\MailViewer\MailViewerServiceProvider" --tag="config" 45 | php artisan vendor:publish --provider="Label84\MailViewer\MailViewerServiceProvider" --tag="migrations" 46 | ``` 47 | 48 | #### 2.1 Publish the views (optional) 49 | 50 | To change the default views, you can publish them to your application. 51 | 52 | ```sh 53 | php artisan vendor:publish --provider="Label84\MailViewer\MailViewerServiceProvider" --tag="views" 54 | ``` 55 | 56 | ### 3. Run migrations 57 | 58 | Run the migration command. 59 | 60 | ```sh 61 | php artisan migrate 62 | ``` 63 | 64 | ## Usage 65 | 66 | To preview the mails sent by your application visit: `/admin/mailviewer`. You can change this url in the config file. 67 | 68 | You can add `MAILVIEWER_ENABLED=true` to your `.env` file. 69 | 70 | ### Filters 71 | 72 | You can filter the mails in the overview with query parameters - example `/admin/mailviewer?notification=WelcomeMail`. 73 | 74 | | Parameter | Value | Example | 75 | |:--------------|:-----------------------------------------|:------------------| 76 | | to= | email | [info@example.com](info@example.com) | 77 | | cc= | email | [info@example.com](info@example.com) | 78 | | bcc= | email | [info@example.com](info@example.com) | 79 | | notification= | class basename of Notification | VerifyEmail | 80 | | from= | [Carbon](https://carbon.nesbot.com/docs) | 2 hours ago | 81 | | till= | [Carbon](https://carbon.nesbot.com/docs) | yesterday | 82 | | around= | [Carbon](https://carbon.nesbot.com/docs) | 2020-12-24 06:00 | 83 | 84 | The 'notification' parameter only requires the class basename (ie. \Illuminate\Auth\Notifications\VerifyEmail = VerifyEmail). 85 | 86 | The around parameter show all mails sent around the given time. By default is will show all mails sent 10 minutes before and 10 minutes after the given time. You can customize the number of minutes by adding an additional &d=X parameter where X is the number of minutes. 87 | 88 | ### Analytics 89 | 90 | ![MailViewer Analytics screenshot](./docs/screenshot-analytics.png?raw=true "MailViewer Analytics Screenshot") 91 | 92 | To preview the analytics page visit: `/admin/mailviewer/analytics`. You can change this url in the config file. 93 | 94 | On the analytics page you can view the number of mails sent per Notification and the latest time this notification was sent. 95 | 96 | ### Examples 97 | 98 | #### Example #1 99 | 100 | View all VerifyEmail mails to [info@example.com](info@example.com). 101 | 102 | `/admin/mailviewer?to=info@example.com¬ification=VerifyEmail` 103 | 104 | #### Example #2 105 | 106 | View all mails sent in the last 2 hours. 107 | 108 | `/admin/mailviewer?from=2 hours ago` 109 | 110 | ### Exclusion list 111 | 112 | In the config file you can add an array of Notification classes and an array of email addresses that should be excluded. Those notifications and email addresses won't be saved to the database. 113 | 114 | ## Tests 115 | 116 | ```sh 117 | composer analyse 118 | composer test 119 | ``` 120 | 121 | ## License 122 | 123 | [MIT](https://opensource.org/licenses/MIT) 124 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "label84/laravel-mailviewer", 3 | "description": "View mails sent by Laravel in the browser", 4 | "type": "library", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Label84", 9 | "email": "info@label84.com" 10 | } 11 | ], 12 | "require": { 13 | "php": "^8.2", 14 | "illuminate/auth": "^11.0|^12.0", 15 | "illuminate/routing": "^11.0|^12.0", 16 | "illuminate/support": "^11.0|^12.0", 17 | "illuminate/database": "^11.0|^12.0" 18 | }, 19 | "require-dev": { 20 | "orchestra/testbench": "^9.0|^10.0", 21 | "larastan/larastan": "^3.1", 22 | "laravel/pint": "^1.21" 23 | }, 24 | "extra": { 25 | "laravel": { 26 | "providers": [ 27 | "Label84\\MailViewer\\MailViewerServiceProvider" 28 | ] 29 | } 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "Label84\\MailViewer\\": "src" 34 | } 35 | }, 36 | "autoload-dev": { 37 | "psr-4": { 38 | "Label84\\MailViewer\\Tests\\": "tests" 39 | } 40 | }, 41 | "scripts": { 42 | "analyse": "vendor/bin/phpstan analyse", 43 | "test": "vendor/bin/phpunit" 44 | }, 45 | "minimum-stability": "dev", 46 | "prefer-stable": true 47 | } 48 | -------------------------------------------------------------------------------- /config/mailviewer.php: -------------------------------------------------------------------------------- 1 | env('MAILVIEWER_ENABLED', true), 11 | 12 | /* 13 | * Table name in the database 14 | */ 15 | 'table_name' => 'mail_viewer_items', 16 | 17 | /** 18 | * Database connection to use 19 | */ 20 | 'database_connection' => env('DB_CONNECTION', 'mysql'), 21 | 22 | 'route' => [ 23 | /** 24 | * The prefix for routes 25 | */ 26 | 'prefix' => '/admin/mailviewer', 27 | 28 | /** 29 | * The middleware to use for all routes 30 | */ 31 | 'middleware' => [ 32 | 'web', 33 | // 'auth', 34 | // TODO: add your (admin) middleware to prevent unwanted access 35 | ], 36 | ], 37 | 38 | 'view' => [ 39 | /** 40 | * Sets the name on the overview page 41 | */ 42 | 'title' => 'MailViewer', 43 | 44 | /** 45 | * Sets the name on the analytics page 46 | */ 47 | 'analytics_title' => 'MailViewer Analytics', 48 | 49 | /** 50 | * Sets the number of items per page on the overview page 51 | */ 52 | 'items_per_page' => 50, 53 | 54 | /* 55 | * Open the mail in a new tab or in the same tab 56 | */ 57 | 'use_tabs' => false, 58 | 59 | /** 60 | * Show the mailer information on the overview page 61 | */ 62 | 'show_mailer' => true, 63 | 64 | /** 65 | * Sets the preferred URL for the 'Back to Laravel' link 66 | */ 67 | 'back_to_application_link_url' => '/', 68 | 69 | /** 70 | * Set the title for the 'Back to Laravel' link 71 | */ 72 | 'back_to_application_link_title' => 'Back to Laravel', 73 | ], 74 | 75 | 'database' => [ 76 | 'include' => [ 77 | /** 78 | * Store additional message data to the headers column 79 | */ 80 | 'headers' => true, 81 | /** 82 | * Store the body of the message in the database 83 | */ 84 | 'body' => true, 85 | ], 86 | 87 | 'exclude' => [ 88 | /* 89 | * Notifications to exclude from being stored in the database 90 | */ 91 | 'notification' => [ 92 | // '\Illuminate\Auth\Notifications\ResetPassword', 93 | ], 94 | 95 | /* 96 | * Notifications to email addresses to exclude from being stored in the database 97 | */ 98 | 'email' => [ 99 | // 'info@example.com', 100 | ], 101 | ], 102 | ], 103 | ]; 104 | -------------------------------------------------------------------------------- /database/migrations/create_mail_viewer_items_table.php.stub: -------------------------------------------------------------------------------- 1 | create(config('mailviewer.table_name'), function (Blueprint $table) { 12 | $table->uuid('uuid')->primary(); 13 | 14 | $table->string('event_type'); 15 | $table->string('mailer'); 16 | 17 | $table->text('headers')->nullable(); 18 | $table->text('recipients'); 19 | 20 | $table->string('notification')->nullable(); 21 | 22 | $table->string('subject')->nullable(); 23 | $table->text('body')->nullable(); 24 | 25 | $table->string('sent_at'); 26 | }); 27 | } 28 | 29 | public function down() 30 | { 31 | Schema::connection(config('mailviewer.database_connection'))->dropIfExists(config('mailviewer.table_name')); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /docs/screenshot-analytics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Label84/laravel-mailviewer/9c10ed20caf3c8bd4e08e552b627f46a35d8fa71/docs/screenshot-analytics.png -------------------------------------------------------------------------------- /docs/screenshot-default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Label84/laravel-mailviewer/9c10ed20caf3c8bd4e08e552b627f46a35d8fa71/docs/screenshot-default.png -------------------------------------------------------------------------------- /phpstan.neon.dist: -------------------------------------------------------------------------------- 1 | includes: 2 | - ./vendor/larastan/larastan/extension.neon 3 | 4 | parameters: 5 | 6 | paths: 7 | - src 8 | - database 9 | - routes 10 | - config 11 | 12 | level: 8 13 | 14 | ignoreErrors: 15 | - identifier: missingType.iterableValue 16 | - identifier: missingType.generics 17 | - identifier: larastan.noEnvCallsOutsideOfConfig 18 | - identifier: argument.type 19 | - 20 | message: '#Unable to resolve the template type TKey in call to function collect#' 21 | path: src/Models/MailViewerItem.php 22 | - 23 | message: '#Unable to resolve the template type TValue in call to function collect#' 24 | path: src/Models/MailViewerItem.php 25 | 26 | 27 | excludePaths: 28 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ./tests 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | src/ 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /resources/views/analytics.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | {{ config('mailviewer.view.title', 'MailViewer') }} 11 | 12 | 13 | 14 |
15 |
16 |

17 | 18 | {{ config('mailviewer.view.analytics_title', 'MailViewer Analytics') }} 19 | 20 | 21 | @if(config('mailviewer.view.show_mailer')) 22 | 23 | Mailer: {{ config('mail.default') }} 24 | 25 | @endif 26 |

27 |

28 | 29 | 30 | 31 | 32 | Back to overview 33 | 34 |

35 |
36 | 37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | @foreach($items as $item) 48 | 49 | 54 | 57 | 62 | 63 | @endforeach 64 | 65 |
Notification#Last sent at
50 | 51 | {{ class_basename($item->name) }} 52 | 53 | 55 | {{ $item->total }} 56 | 58 | 59 | {{ Carbon\Carbon::parse($item->last_sent_at)->diffForHumans() }} 60 | 61 |
66 |
67 |
68 | 69 | 70 | -------------------------------------------------------------------------------- /resources/views/index.blade.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | {{ config('mailviewer.view.title', 'MailViewer') }} 11 | 12 | 13 | 14 |
15 |
16 |

17 | 18 | {{ config('mailviewer.view.title', 'MailViewer') }} 19 | 20 | 21 | @if(config('mailviewer.view.show_mailer')) 22 | 23 | Mailer: {{ config('mail.default') }} 24 | 25 | @endif 26 |

27 | 41 |
42 | 43 |
44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | @foreach($mails as $mail) 55 | 56 | 61 | 70 | 79 | 86 | 87 | @endforeach 88 | 89 |
NotificationSubjectRecipientsDate
57 | 58 | {{ class_basename($mail->notification) }} 59 | 60 | 62 | @if($mail->body) 63 | 64 | {{ $mail->subject }} 65 | 66 | @else 67 | {{ $mail->subject }} 68 | @endif 69 | 71 | @foreach($mail->to_recipients as $recipient) 72 | {{ $recipient }}
73 | @endforeach 74 | 75 | @foreach($mail->cc_recipients as $recipient) 76 | cc: {{ $recipient }}
77 | @endforeach 78 |
80 | 81 | 82 | {{ $mail->sent_at->diffForHumans() }} 83 | 84 | 85 |
90 |
91 | 92 |
93 | {{ $mails->appends(request()->query())->links() }} 94 |
95 |
96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /routes/web.php: -------------------------------------------------------------------------------- 1 | name('mailviewer.index'); 7 | Route::get('/analytics', [MailViewerController::class, 'analytics'])->name('mailviewer.analytics'); 8 | Route::get('/{mailViewerItem:uuid}', [MailViewerController::class, 'show'])->name('mailviewer.show'); 9 | -------------------------------------------------------------------------------- /src/Http/Controllers/MailViewerController.php: -------------------------------------------------------------------------------- 1 | query('notification', null); 19 | 20 | $mails = MailViewerItem::query() 21 | ->when($request->query('to'), fn ($query) => $query->whereJsonContains('recipients->to', [$request->query('to')])) 22 | ->when($request->query('cc'), fn ($query) => $query->whereJsonContains('recipients->cc', [$request->query('cc')])) 23 | ->when($request->query('bcc'), fn ($query) => $query->whereJsonContains('recipients->bcc', [$request->query('bcc')])) 24 | ->when($request->query('notification'), fn ($query) => $query->where('notification', 'LIKE', "%{$notification}")) 25 | ->when($request->query('from'), fn ($query) => $query->whereDate('sent_at', '>=', Carbon::parse($request->query('from')))) 26 | ->when($request->query('till'), fn ($query) => $query->whereDate('sent_at', '<=', Carbon::parse($request->query('till')))) 27 | ->when($request->query('around'), function ($query) use ($request) { 28 | return $query->whereBetween('sent_at', [ 29 | Carbon::parse($request->query('around'))->subMinutes((int) $request->query('d', 10)), 30 | Carbon::parse($request->query('around'))->addMinutes((int) $request->query('d', 10)), 31 | ]); 32 | }) 33 | ->paginate(config('mailviewer.view.items_per_page', 50)); 34 | 35 | return view('mailviewer::index', compact('mails')); 36 | } 37 | 38 | public function show(string $uuid): Response 39 | { 40 | $mailViewerItem = MailViewerItem::where('uuid', $uuid)->firstOrFail(); 41 | 42 | return response($mailViewerItem->body); 43 | } 44 | 45 | public function analytics(): View 46 | { 47 | $items = DB::table(config('mailviewer.table_name')) 48 | ->whereNotNull('notification') 49 | ->select([ 50 | DB::raw('notification AS name'), 51 | DB::raw('count(*) AS total'), 52 | DB::raw('MAX(sent_at) AS last_sent_at'), 53 | ]) 54 | ->groupBy('notification') 55 | ->orderByDesc('total') 56 | ->get(); 57 | 58 | return view('mailviewer::analytics', compact('items')); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Listeners/CreateMailViewerItem.php: -------------------------------------------------------------------------------- 1 | shouldLog($event)) { 17 | return; 18 | } 19 | 20 | /** @var \Symfony\Component\Mime\Email $message */ 21 | $message = $event->message; 22 | 23 | MailViewerItem::create([ 24 | 'event_type' => MessageSent::class, 25 | 'mailer' => config('mail.default') ?? '', 26 | 'headers' => $this->formatHeaders($message->getHeaders()), 27 | 'notification' => $event->data['__laravel_notification'] ?? null, 28 | 'recipients' => $this->formatRecipients($message), 29 | 'subject' => $message->getSubject(), 30 | 'body' => config('mailviewer.database.include.body', true) ? $message->getHtmlBody() : null, 31 | 'sent_at' => Carbon::now()->timezone(config('app.timezone', 'UTC')), 32 | ]); 33 | } 34 | 35 | private function formatHeaders(Headers $headers): ?array 36 | { 37 | if (! config('mailviewer.database.include.headers')) { 38 | return null; 39 | } 40 | 41 | return [ 42 | 'date' => $headers->get('date'), 43 | 'message-id' => $this->getMessageId($headers), 44 | 'from' => $headers->get('from'), 45 | ]; 46 | } 47 | 48 | private function getMessageId(Headers $headers): mixed 49 | { 50 | $messageId = $headers->get('message-id'); 51 | 52 | if ($messageId instanceof \Symfony\Component\Mime\Header\UnstructuredHeader) { 53 | return $messageId->getBodyAsString(); 54 | } 55 | 56 | if ($messageId instanceof \Symfony\Component\Mime\Header\IdentificationHeader) { 57 | return $messageId->getIds(); 58 | } 59 | 60 | if (is_object($messageId)) { 61 | return $messageId->toString(); 62 | } 63 | 64 | return $messageId; 65 | } 66 | 67 | private function formatRecipients(Email $message): array 68 | { 69 | return array_merge( 70 | ['to' => (new Collection($message->getTo()))->map(fn ($address) => $address->getAddress())->toArray()], 71 | ['cc' => (new Collection($message->getCc()))->map(fn ($address) => $address->getAddress())->toArray()], 72 | ['bcc' => (new Collection($message->getBcc()))->map(fn ($address) => $address->getAddress())->toArray()], 73 | ); 74 | } 75 | 76 | private function shouldLog(MessageSent $event): bool 77 | { 78 | /* Make sure package is enabled */ 79 | if (! config('mailviewer.enabled')) { 80 | return false; 81 | } 82 | 83 | /* Make sure notification is not in list of excluded notifications */ 84 | if (isset($event->data['__laravel_notification']) && in_array($event->data['__laravel_notification'], config('mailviewer.database.exclude.notification') ?? [])) { 85 | return false; 86 | } 87 | 88 | /* Make sure recipient is not in list of excluded email addresses */ 89 | if ($event->message->getTo() && count((new Collection($event->message->getTo())) 90 | ->map(fn ($address) => $address->getAddress()) 91 | ->reject(fn ($email) => in_array($email, config('mailviewer.database.exclude.email') ?? []))) == 0) { 92 | return false; 93 | } 94 | 95 | return true; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/MailViewerServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 15 | $this->publishes([ 16 | __DIR__.'/../config/mailviewer.php' => config_path('mailviewer.php'), 17 | ], 'config'); 18 | 19 | $this->publishes([ 20 | __DIR__.'/../resources/views' => resource_path('views/vendor/mailviewer'), 21 | ], 'views'); 22 | 23 | if (! class_exists('CreateMailViewerItems')) { 24 | $this->publishes([ 25 | __DIR__.'/../database/migrations/create_mail_viewer_items_table.php.stub' => database_path('migrations/'.date('Y_m_d_His', time()).'_create_mail_viewer_items_table.php'), 26 | ], 'migrations'); 27 | } 28 | } 29 | 30 | $this->registerRoutes(); 31 | 32 | $this->loadViewsFrom(__DIR__.'/../resources/views', 'mailviewer'); 33 | } 34 | 35 | public function register(): void 36 | { 37 | $this->mergeConfigFrom( 38 | __DIR__.'/../config/mailviewer.php', 39 | 'mailviewer' 40 | ); 41 | 42 | Event::subscribe(MessageSentSubscriber::class); 43 | } 44 | 45 | protected function registerRoutes(): void 46 | { 47 | Route::group($this->routeConfiguration(), function () { 48 | $this->loadRoutesFrom(__DIR__.'/../routes/web.php'); 49 | }); 50 | } 51 | 52 | protected function routeConfiguration(): array 53 | { 54 | return [ 55 | 'prefix' => config('mailviewer.route.prefix'), 56 | 'middleware' => config('mailviewer.route.middleware'), 57 | ]; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Models/MailViewerItem.php: -------------------------------------------------------------------------------- 1 | setTable(config('mailviewer.table_name', 'mail_viewer_items')); 26 | $this->setConnection(config('mailviewer.database_connection', 'mysql')); 27 | } 28 | 29 | public static function booted(): void 30 | { 31 | static::creating(function (self $mailViewerItem) { 32 | $mailViewerItem->uuid = Str::uuid(); 33 | }); 34 | 35 | static::addGlobalScope('order', function (Builder $builder) { 36 | $builder->orderBy('sent_at', 'desc'); 37 | }); 38 | } 39 | 40 | protected static function newFactory(): MailViewerItemFactory 41 | { 42 | return MailViewerItemFactory::new(); 43 | } 44 | 45 | public function getRouteKeyName(): string 46 | { 47 | return 'uuid'; 48 | } 49 | 50 | public $incrementing = false; 51 | 52 | public $timestamps = false; 53 | 54 | protected $guarded = [ 55 | 'uuid', 56 | ]; 57 | 58 | protected $casts = [ 59 | 'sent_at' => 'datetime', 60 | 'headers' => 'array', 61 | 'recipients' => 'array', 62 | ]; 63 | 64 | public function getRecipientsAttribute(string $value): ?Collection 65 | { 66 | return collect(json_decode($value)); 67 | } 68 | 69 | public function setRecipientsAttribute(array $value): void 70 | { 71 | $this->attributes['recipients'] = json_encode($value); 72 | } 73 | 74 | public function getToRecipientsAttribute(): Collection 75 | { 76 | return collect($this->recipients['to'] ?? []); 77 | } 78 | 79 | public function getCcRecipientsAttribute(): Collection 80 | { 81 | return collect($this->recipients['cc'] ?? []); 82 | } 83 | 84 | public function getBccRecipientsAttribute(): Collection 85 | { 86 | return collect($this->recipients['bcc'] ?? []); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/Providers/EventServiceProvider.php: -------------------------------------------------------------------------------- 1 | [ 13 | CreateMailViewerItem::class, 14 | ], 15 | ]; 16 | 17 | public function boot(): void 18 | { 19 | parent::boot(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Subscribers/MessageSentSubscriber.php: -------------------------------------------------------------------------------- 1 | listen(MessageSent::class, [CreateMailViewerItem::class, 'handle']); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tests/Config/ConfigTest.php: -------------------------------------------------------------------------------- 1 | set('mailviewer.enabled', false); 20 | 21 | Notification::route('mail', 'info@example.com')->notify(new TestNotification); 22 | 23 | $this->assertCount(0, MailViewerItem::all()); 24 | } 25 | 26 | public function test_it_does_not_create_an_item_when_notification_is_in_exclude_notification_list() 27 | { 28 | config()->set('mailviewer.database.exclude.notification', [ 29 | TestNotification::class, 30 | ]); 31 | 32 | Notification::route('mail', 'info@example.com')->notify(new TestNotification); 33 | 34 | $this->assertCount(0, MailViewerItem::all()); 35 | } 36 | 37 | public function test_it_does_not_create_an_item_when_email_is_in_exclude_email_list() 38 | { 39 | config()->set('mailviewer.database.exclude.email', [ 40 | 'info@example.com', 41 | ]); 42 | 43 | Notification::route('mail', 'info@example.com')->notify(new TestNotification); 44 | 45 | $this->assertCount(0, MailViewerItem::all()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tests/Database/Factories/MailViewerItemFactory.php: -------------------------------------------------------------------------------- 1 | MessageSent::class, 17 | 'mailer' => $this->faker->randomElement([ 18 | 'smtp', 19 | 'postmark', 20 | 'log', 21 | ]), 22 | 'headers' => null, 23 | 'notification' => $this->faker->randomElement([ 24 | '\Illuminate\Auth\Notifications\ResetPassword', 25 | '\Illuminate\Auth\Notifications\VerifyEmail', 26 | ]), 27 | 'recipients' => ['to' => [$this->faker->safeEmail, $this->faker->safeEmail], 'cc' => [], 'bcc' => []], 28 | 'subject' => $this->faker->sentence, 29 | 'body' => $this->faker->randomHtml(2, 3), 30 | 'sent_at' => $this->faker->dateTimeBetween('-30 days', 'today'), 31 | ]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /tests/Events/ListensOnMailEventsTest.php: -------------------------------------------------------------------------------- 1 | notify(new TestNotification); 20 | 21 | $this->assertCount(1, MailViewerItem::all()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tests/Events/Notifications/TestNotification.php: -------------------------------------------------------------------------------- 1 | line('The introduction to the notification.') 19 | ->action('Notification Action', url('/')) 20 | ->line('Thank you for using our application!'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tests/Models/MailViewerItemTest.php: -------------------------------------------------------------------------------- 1 | assertTrue( 21 | Schema::hasColumns(with(new MailViewerItem)->getTable(), [ 22 | 'uuid', 23 | 'event_type', 24 | 'mailer', 25 | 'headers', 26 | 'recipients', 27 | 'notification', 28 | 'subject', 29 | 'body', 30 | 'sent_at', 31 | ]) 32 | ); 33 | } 34 | 35 | public function test_it_will_set_an_uuid_when_created() 36 | { 37 | $item = MailViewerItem::factory()->create(); 38 | 39 | $this->assertTrue(preg_match(LazyUuidFromString::VALID_REGEX, $item->uuid) === 1); 40 | } 41 | 42 | public function test_it_orders_items_by_date_desc_by_default() 43 | { 44 | $this->assertEquals((new MailViewerItem)->getGlobalScope('order'), function (Builder $builder) { 45 | $builder->orderBy('sent_at', 'desc'); 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | setUpDatabase(); 19 | } 20 | 21 | protected function getPackageProviders($app): array 22 | { 23 | return [ 24 | MailViewerServiceProvider::class, 25 | ]; 26 | } 27 | 28 | protected function getEnvironmentSetUp($app): void 29 | { 30 | config()->set('mailviewer.database_connection', 'sqlite'); 31 | config()->set('database.default', 'sqlite'); 32 | config()->set('database.connections.sqlite', [ 33 | 'driver' => 'sqlite', 34 | 'database' => ':memory:', 35 | ]); 36 | } 37 | 38 | protected function setUpDatabase() 39 | { 40 | Schema::create(config('mailviewer.table_name'), function (Blueprint $table) { 41 | $table->uuid('uuid')->primary(); 42 | 43 | $table->string('event_type'); 44 | $table->string('mailer'); 45 | 46 | $table->text('headers')->nullable(); 47 | $table->text('recipients'); 48 | 49 | $table->string('notification')->nullable(); 50 | 51 | $table->string('subject')->nullable(); 52 | $table->text('body')->nullable(); 53 | 54 | $table->string('sent_at'); 55 | }); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /tests/Views/ViewTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('/admin/mailviewer', config('mailviewer.route.prefix')); 19 | } 20 | 21 | public function test_it_has_web_as_default_middleware() 22 | { 23 | $this->assertEquals(['web'], config('mailviewer.route.middleware')); 24 | } 25 | 26 | public function test_it_does_not_have_auth_as_default_middleware() 27 | { 28 | $this->assertNotContains(['auth'], config('mailviewer.route.middleware')); 29 | } 30 | 31 | public function test_it_can_list_the_mail_viewer_items() 32 | { 33 | $response = $this->withoutMiddleware()->get(route('mailviewer.index')); 34 | 35 | $response->assertSuccessful(); 36 | 37 | $response->assertViewHas('mails', MailViewerItem::paginate(50)); 38 | } 39 | 40 | public function test_it_can_list_the_mail_viewer_items_with_to_cc_bcc_query_filter() 41 | { 42 | MailViewerItem::factory()->create([ 43 | 'recipients' => ['to' => ['test@example.com'], 'cc' => [], 'bcc' => []], 44 | ]); 45 | 46 | // TODO default testing database connection doesn't support JSON CONTAINS operation 47 | $response = $this->withoutMiddleware()->get(route('mailviewer.index', ['to_X' => 'test@example.com'])); 48 | 49 | $response->assertSuccessful(); 50 | 51 | $response->assertViewHas('mails'); 52 | } 53 | 54 | public function test_it_can_list_the_mail_viewer_items_with_notification_base_class_query_filter() 55 | { 56 | $class = class_basename(\Illuminate\Auth\Notifications\VerifyEmail::class); 57 | 58 | $response = $this->withoutMiddleware()->get(route('mailviewer.index', ['notification' => $class])); 59 | 60 | $response->assertSuccessful(); 61 | 62 | $response->assertViewHas('mails', MailViewerItem::where('notification', '\Illuminate\Auth\Notifications\VerifyEmail') 63 | ->paginate(50) 64 | ->appends(['notification' => $class])); 65 | } 66 | 67 | public function test_it_can_list_the_mail_viewer_items_with_from_query_filter() 68 | { 69 | collect(range(1, 50))->each(function (int $i) { 70 | MailViewerItem::factory()->create([ 71 | 'sent_at' => today()->subDays($i)->startOfDay(), 72 | ]); 73 | }); 74 | 75 | $this->assertCount(50, MailViewerItem::all()); 76 | 77 | $fromDate = today()->subDays(20)->format('Y-m-d'); 78 | 79 | $response = $this->withoutMiddleware()->get(route('mailviewer.index', ['from' => $fromDate])); 80 | 81 | $response->assertSuccessful(); 82 | 83 | $response->assertViewHas('mails', MailViewerItem::whereDate('sent_at', '>=', $fromDate) 84 | ->paginate(50) 85 | ->appends(['from' => $fromDate])); 86 | } 87 | 88 | public function test_it_can_list_the_mail_viewer_items_with_till_query_filter() 89 | { 90 | collect(range(1, 50))->each(function (int $i) { 91 | MailViewerItem::factory()->create([ 92 | 'sent_at' => today()->subDays($i)->startOfDay(), 93 | ]); 94 | }); 95 | 96 | $this->assertCount(50, MailViewerItem::all()); 97 | 98 | $tillDate = today()->subDays(20)->format('Y-m-d'); 99 | 100 | $response = $this->withoutMiddleware()->get(route('mailviewer.index', ['till' => $tillDate])); 101 | 102 | $response->assertSuccessful(); 103 | 104 | $response->assertViewHas('mails', MailViewerItem::whereDate('sent_at', '<=', $tillDate) 105 | ->paginate(50) 106 | ->appends(['till' => $tillDate])); 107 | } 108 | 109 | public function test_it_can_list_the_mail_viewer_items_with_around_query_filter() 110 | { 111 | collect(range(1, 50))->each(function (int $i) { 112 | MailViewerItem::factory()->create([ 113 | 'sent_at' => now()->subMinutes($i), 114 | ]); 115 | }); 116 | 117 | $this->assertCount(50, MailViewerItem::all()); 118 | 119 | $aroundTime = now()->format('Y-m-d H:i'); 120 | 121 | $response = $this->withoutMiddleware()->get(route('mailviewer.index', ['around' => $aroundTime])); 122 | 123 | $response->assertSuccessful(); 124 | 125 | $response->assertViewHas('mails', MailViewerItem::whereBetween('sent_at', [ 126 | Carbon::createFromFormat('Y-m-d H:i', $aroundTime)->subMinutes(10), 127 | Carbon::createFromFormat('Y-m-d H:i', $aroundTime)->addMinutes(10), 128 | ]) 129 | ->paginate(50) 130 | ->appends(['around' => $aroundTime])); 131 | } 132 | 133 | public function test_it_can_list_the_mail_viewer_items_with_around_and_d_query_filter() 134 | { 135 | collect(range(1, 50))->each(function (int $i) { 136 | MailViewerItem::factory()->create([ 137 | 'sent_at' => now()->subMinutes($i), 138 | ]); 139 | }); 140 | 141 | $this->assertCount(50, MailViewerItem::all()); 142 | 143 | $aroundTime = now()->format('Y-m-d H:i'); 144 | 145 | $response = $this->withoutMiddleware()->get(route('mailviewer.index', [ 146 | 'around' => $aroundTime, 147 | 'd' => 5, 148 | ])); 149 | 150 | $response->assertSuccessful(); 151 | 152 | $response->assertViewHas('mails', MailViewerItem::whereBetween('sent_at', [ 153 | Carbon::createFromFormat('Y-m-d H:i', $aroundTime)->subMinutes(5), 154 | Carbon::createFromFormat('Y-m-d H:i', $aroundTime)->addMinutes(5), 155 | ]) 156 | ->paginate(50) 157 | ->appends(['around' => $aroundTime, 'd' => 5])); 158 | } 159 | 160 | public function test_it_has_pagination_when_item_count_is_more_than_item_per_page() 161 | { 162 | MailViewerItem::factory()->count(60)->create(); 163 | 164 | $response = $this->withoutMiddleware()->get(route('mailviewer.index')); 165 | 166 | $response->assertSuccessful(); 167 | 168 | $this->assertDatabaseCount('mail_viewer_items', 60); 169 | 170 | $response->assertViewHas('mails', MailViewerItem::paginate(50)); 171 | } 172 | 173 | public function test_it_can_show_the_mail_viewer_item_preview() 174 | { 175 | MailViewerItem::factory()->create(); 176 | 177 | $response = $this->withoutMiddleware()->get(route('mailviewer.show', MailViewerItem::first())); 178 | 179 | $response->assertSuccessful(); 180 | } 181 | 182 | public function test_it_can_show_the_mail_viewer_analytics() 183 | { 184 | MailViewerItem::factory()->count(20)->create(); 185 | 186 | $response = $this->withoutMiddleware()->get(route('mailviewer.analytics')); 187 | 188 | $response->assertSuccessful(); 189 | 190 | $response->assertViewHas('items'); 191 | } 192 | } 193 | --------------------------------------------------------------------------------