diff --git a/Service/MailgunTransport.php b/Service/MailgunTransport.php index 43ccc8c..b11b3e2 100644 --- a/Service/MailgunTransport.php +++ b/Service/MailgunTransport.php @@ -112,6 +112,14 @@ public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = nul $failedRecipients = $postData['to']; $sent = 0; $resultStatus = Swift_Events_SendEvent::RESULT_FAILED; + + $errorMessage = $e->getCode() . ' : ' . $e->getMessage(); + if ($failEvt = $this->eventDispatcher->createResponseEvent($this, $errorMessage, false)) { + $this->eventDispatcher->dispatchEvent($failEvt, 'responseReceived'); + if ($failEvt->bubbleCancelled()) { + return 0; + } + } } if ($evt) { diff --git a/Tests/Service/MailgunTransportTest.php b/Tests/Service/MailgunTransportTest.php index 22ff33a..103d4b3 100644 --- a/Tests/Service/MailgunTransportTest.php +++ b/Tests/Service/MailgunTransportTest.php @@ -150,6 +150,63 @@ public function testSendMessageWithException() $this->assertEquals(['bob@example.com', 'eve@example.com', 'tobias@example.com'], $failed); } + public function testSendMessageWithExceptionLogged() + { + $exceptionMsg = 'Your credentials are incorrect.'; + $exceptionCode = 401; + + $responseEvt = $this->getMockBuilder('Swift_Events_ResponseEvent') + ->setMethods(['getResponse', 'isValid']) + ->disableOriginalConstructor() + ->getMock(); + $responseEvt->expects($this->any()) + ->method('isValid') + ->will($this->returnValue(true)); + $responseEvt->expects($this->any()) + ->method('getResponse') + ->will($this->returnValue('')); + + // Ensure dispatcher sends the responseReceived event + $dispatcher = $this->getMockBuilder('Swift_Events_SimpleEventDispatcher') + ->setMethods(['createSendEvent', 'createResponseEvent', 'dispatchEvent']) + ->getMock(); + $dispatcher->expects($this->once()) + ->method('createResponseEvent') + ->will($this->returnValue($responseEvt)); + $dispatcher->expects($this->once()) + ->method('dispatchEvent') + ->with($responseEvt, 'responseReceived'); + + $mailgun = $this->getMockBuilder('Mailgun\Mailgun')->getMock(); + $transport = new MailgunTransport($dispatcher, $mailgun, 'default.com'); + + $messageApi = $this->getMockBuilder('Mailgun\Api\Message') + ->disableOriginalConstructor() + ->getMock(); + + $messageApi->expects($this->once()) + ->method('sendMime') + ->will($this->throwException(new UnknownErrorException($exceptionMsg, $exceptionCode))); + + $mailgun->expects($this->once()) + ->method('messages') + ->willReturn($messageApi); + + + $message = (new \Swift_Message('Foobar')) + ->setFrom('alice@example.com') + ->setTo('bob@example.com') + ->setCc('tobias@example.com') + ->setBcc('eve@example.com') + ->setBody('Message body'); + + $failed = null; + $sent = $transport->send($message, $failed); + + $this->assertEquals(0, $sent); + $this->assertEquals(['bob@example.com', 'eve@example.com', 'tobias@example.com'], $failed); + } + /** * @return MailgunTransport */