diff --git a/src/Routing/Router.php b/src/Routing/Router.php index 390d839..ab81ba0 100644 --- a/src/Routing/Router.php +++ b/src/Routing/Router.php @@ -84,22 +84,25 @@ protected function createRoute(string $subject, string $pattern, $action): Route public function callMailboxes(InboundEmail $email) { if ($email->isValid()) { - $matchedRoutes = $this->routes->match($email)->map(function (Route $route) use ($email) { - $route->run($email); - }); - - if ($matchedRoutes->isEmpty() && $this->fallbackRoute) { - $matchedRoutes[] = $this->fallbackRoute; - $this->fallbackRoute->run($email); - } - - if ($this->catchAllRoute) { - $matchedRoutes[] = $this->catchAllRoute; - $this->catchAllRoute->run($email); - } - - if ($this->shouldStoreInboundEmails() && $this->shouldStoreAllInboundEmails($matchedRoutes)) { - $this->storeEmail($email); + $matchedRoutes = $this->routes->match($email); + try { + $matchedRoutes->map(function (Route $route) use ($email) { + $route->run($email); + }); + + if ($matchedRoutes->isEmpty() && $this->fallbackRoute) { + $matchedRoutes[] = $this->fallbackRoute; + $this->fallbackRoute->run($email); + } + + if ($this->catchAllRoute) { + $matchedRoutes[] = $this->catchAllRoute; + $this->catchAllRoute->run($email); + } + } finally { + if ($this->shouldStoreInboundEmails() && $this->shouldStoreAllInboundEmails($matchedRoutes)) { + $this->storeEmail($email); + } } } } @@ -111,7 +114,7 @@ protected function shouldStoreInboundEmails(): bool protected function shouldStoreAllInboundEmails(Collection $matchedRoutes): bool { - return $matchedRoutes->isNotEmpty() ? true : ! config('mailbox.only_store_matching_emails'); + return $matchedRoutes->isNotEmpty() || ! config('mailbox.only_store_matching_emails'); } protected function storeEmail(InboundEmail $email) diff --git a/tests/InboundEmailTest.php b/tests/InboundEmailTest.php index 8a54b9a..d593550 100644 --- a/tests/InboundEmailTest.php +++ b/tests/InboundEmailTest.php @@ -43,6 +43,23 @@ public function it_stores_all_inbound_emails() $this->assertSame(2, InboundEmail::query()->count()); } + /** @test */ + public function it_stores_all_inbound_emails_on_exception() + { + $this->app['config']['mailbox.only_store_matching_emails'] = false; + + Mailbox::to('someone@beyondco.de', function ($email) { + throw new \Exception("expect to fail"); + }); + + try { + Mail::to('someone@beyondco.de')->send(new TestMail); + } catch(\Throwable $e){} + Mail::to('someone-else@beyondco.de')->send(new TestMail); + + $this->assertSame(2, InboundEmail::query()->count()); + } + /** @test */ public function it_can_use_fallbacks() {