Skip to content

Commit

Permalink
+ fix #1
Browse files Browse the repository at this point in the history
+ added ability to show embedded images in the resulting mail log
+ added command to clear old email entries
  • Loading branch information
gabrieliuga committed Jan 23, 2020
1 parent 38224ae commit a3a7936
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 14 deletions.
24 changes: 24 additions & 0 deletions README.md
Expand Up @@ -22,6 +22,30 @@ composer require gabrieliuga/laravel-mail-log
artisan migrate

artisan vendor:publish --tag=maillog-config

```
#### Setup auto clear command in app/Console/Kernel.php add ClearOldEmails::class
```php
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
ClearOldEmails::class,
];

/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('giuga:purge-mail-log')->daily();
}

```

### Testing
Expand Down
22 changes: 22 additions & 0 deletions database/migrations/2020_01_22_215032_change_message_column.php
@@ -0,0 +1,22 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class ChangeMessageColumn extends Migration
{
public function up()
{
Schema::table('mail_log', function (Blueprint $table) {
$table->longText('message')->change();
});
}

public function down()
{
Schema::table('mail_log', function (Blueprint $table) {
$table->text('message')->change();
});
}
}
50 changes: 50 additions & 0 deletions src/Commands/ClearOldEmails.php
@@ -0,0 +1,50 @@
<?php

namespace Giuga\LaravelMailLog\Commands;

use Carbon\Carbon;
use Giuga\LaravelMailLog\Models\MailLog;
use Illuminate\Console\Command;

class ClearOldEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'giuga:purge-mail-log';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Remove mails saved before the time defined in the config';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (config('mail-log.purge')) {
$beforeDate = Carbon::now()->subDays(config('mail-log.purge_after'));
$toRemove = MailLog::where('created_at', '<', $beforeDate)->get();
foreach ($toRemove as $item) {
$item->delete();
}
}
}
}
7 changes: 6 additions & 1 deletion src/LaravelMailLogServiceProvider.php
Expand Up @@ -2,6 +2,7 @@

namespace Giuga\LaravelMailLog;

use Giuga\LaravelMailLog\Commands\ClearOldEmails;
use Illuminate\Support\ServiceProvider;

class LaravelMailLogServiceProvider extends ServiceProvider
Expand All @@ -19,6 +20,10 @@ public function boot()
$this->publishes([
__DIR__.'/../config/config.php' => config_path('mail-log.php'),
], 'maillog-config');

$this->commands([
ClearOldEmails::class
]);
}
}

Expand All @@ -31,7 +36,7 @@ public function register()
$this->app->register(MailPolicyServiceProvider::class);

// Automatically apply the package configuration
$this->mergeConfigFrom(__DIR__.'/../config/config.php', 'maillog-config');
$this->mergeConfigFrom(__DIR__.'/../config/config.php', 'mail-log');

// Register the main class to use with the facade
$this->app->singleton('laravel-mail-log', function () {
Expand Down
43 changes: 30 additions & 13 deletions src/Listeners/MailSentListener.php
Expand Up @@ -4,6 +4,7 @@

use Giuga\LaravelMailLog\Models\MailLog;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Support\Facades\Log;

class MailSentListener
{
Expand All @@ -20,22 +21,38 @@ public function __construct()
/**
* Handle the event.
*
* @param object $event
* @param MessageSent $event
* @return void
*/
public function handle(MessageSent $event)
{
$to = $event->message->getTo() ?? [];
$cc = $event->message->getCc() ?? [];
$bcc = $event->message->getBcc() ?? [];
$data = [
'to' => implode(', ', is_array($to) ? array_keys($to) : $to),
'cc' => implode(', ', is_array($cc) ? array_keys($cc) : $cc),
'bcc' => implode(', ', is_array($bcc) ? array_keys($bcc) : $bcc),
'subject' => $event->message->getSubject(),
'message' => $event->message->getBody(),
'data' => [],
];
MailLog::create($data);
try {
$msg = $event->message;
$parts = $msg->getChildren();
$body = $event->message->getBody();
if (! empty($parts)) {
foreach ($parts as $part) {
if (stripos($part->getBodyContentType(), 'image') !== false) {
$ptr = str_replace("\n", '', trim(str_replace($part->getHeaders(), '', $part->toString())));
$body = str_replace('cid:'.$part->getId(), 'data:'.$part->getBodyContentType().';base64,'.$ptr, $body);
}
}
}

$to = $event->message->getTo() ?? [];
$cc = $event->message->getCc() ?? [];
$bcc = $event->message->getBcc() ?? [];
$data = [
'to' => implode(', ', is_array($to) ? array_keys($to) : $to),
'cc' => implode(', ', is_array($cc) ? array_keys($cc) : $cc),
'bcc' => implode(', ', is_array($bcc) ? array_keys($bcc) : $bcc),
'subject' => $event->message->getSubject(),
'message' => $body,
'data' => [],
];
MailLog::create($data);
} catch (\Throwable $e) {
Log::debug('Failed to save mail log ['.$e->getMessage().']');
}
}
}
45 changes: 45 additions & 0 deletions tests/MailLogTest.php
Expand Up @@ -2,9 +2,13 @@

namespace Gabrieliuga\LaravelMailLog\Tests;

use Carbon\Carbon;
use Giuga\LaravelMailLog\Models\MailLog;
use Giuga\LaravelMailLog\Tests\TestCase;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Artisan;
use PHPUnit\Framework\Constraint\DirectoryExists;

class MailLogTest extends TestCase
{
Expand All @@ -28,4 +32,45 @@ public function testMailEventCatch()
$this->assertEquals('test_bcc@example.com', MailLog::first()->bcc);
$this->assertEquals('test_cc@example.com', MailLog::first()->cc);
}

/** @test */
public function testMailImageAttached()
{

$swiftMessage = new \Swift_Message('Test Subject', 'Test Content');
$swiftMessage->addTo('test@example.com');
$swiftMessage->addBcc('test_bcc@example.com');
$swiftMessage->addCc('test_cc@example.com');
$newMsg = new Message($swiftMessage);

$newMsg->setBody('<div>TextContent<img src="'.$newMsg->embed(__DIR__ . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'test.png').'" /></div>');
event(new MessageSent($newMsg->getSwiftMessage(), []));

$this->assertEquals(1, MailLog::all()->count());
$model = MailLog::first();
$this->assertEquals('test@example.com', $model->to);
$this->assertEquals('test_bcc@example.com', $model->bcc);
$this->assertEquals('test_cc@example.com', $model->cc);
$this->assertStringContainsString('<img src="data:image/png;base64,', $model->message);
$this->assertStringNotContainsString('cid:', $model->message);
}

/** @test */
public function testPurgeCommand()
{
MailLog::truncate();
for($x = 0; $x < 100; $x++){
MailLog::create([
'to' => $x . 'example@test.com',
'created_at' => Carbon::now()->subDays($x)
]);
}
$this->assertEquals(100, MailLog::all()->count());
$this->assertEquals(7, config('mail-log.purge_after'));
$this->assertEquals(true, config('mail-log.purge'));

Artisan::call('giuga:purge-mail-log');
$this->assertEquals(8, MailLog::all()->count());

}
}
Binary file added tests/data/test.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit a3a7936

Please sign in to comment.