Lancashireman
Lancashireman

Reputation: 33

Mailgun sendMessage parameter exception

Why is the function sendMessage() throwing an exception here?

$mg = new MailGun('my_actual_api_key');

$response = $mg->sendMessage('my-domain.com', array(
    'from'     => '[email protected]',
    'to'       => '[email protected]',
    'subject'  => 'Test',
    'html'     => '<h1>Test body</h2>'
));

...and the exception I am getting is...

Fatal error: Uncaught exception'Mailgun\Connection\Exceptions\MissingRequiredParameters' with message 'The parameters passed to the API were invalid. Check your inputs!' in C:\wamp\www\sektor\admin\app\application\third_party\MailGun\vendor\mailgun\mailgun-php\src\Mailgun\Connection\RestClient.php on line 127

Apparently the parameters I am sending to the API are wrong but this is following the MailGun API documentation but this clearly doesn't work.

I haven't modified the code of the Mailer class at all.

Upvotes: 3

Views: 4732

Answers (1)

Ivan Jovović
Ivan Jovović

Reputation: 5298

To get a bit more details about that error, use the code from this patch:

Adds the actual response message to the errors thrown on 400, 401 and 404 response codes. This provides a lot more useful info than the current messages. The message doesn’t really give you much to go on. I spent hours trying to find what I did wrong, double checking my API keys and looking up the error on google.

Change source file src/Mailgun/Connection/RestClient.php like this (full patch is at https://github.com/mailgun/mailgun-php/pull/72/files):

When throwing exception EXCEPTION_MISSING_REQUIRED_PARAMETERS, get more info with the method getResponseExceptionMessage() (note + and - signs in front of added and removed lines):

elseif($httpResponseCode == 400){
-           throw new MissingRequiredParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_PARAMETERS);
+           throw new MissingRequiredParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_PARAMETERS . $this->getResponseExceptionMessage($responseObj));
        }

    /**
+     * @param \Guzzle\Http\Message\Response $responseObj
+     * @return string
+     */
+   protected function getResponseExceptionMessage(\Guzzle\Http\Message\Response $responseObj){
+       $body = (string)$responseObj->getBody();
+       $response = json_decode($body);
+       if (json_last_error() == JSON_ERROR_NONE && isset($response->message)) {
+           return " " . $response->message;
+       }
+   }   

Upvotes: 6

Related Questions