phpemailcakephpmailgun

Send mail via MailGun in CakePHP


i run a cloud app (using CakePHP) on Rackspace and i wanna send emails using cakephp. I used this: https://github.com/kochb/cakephp-mailgun but it returns me an

 "Could not send email.

Error: An Internal Error Has Occurred." 

error. The way i try to send an email is with the following code:

$Email = new CakeEmail();


          $from = $this->request->data['Mail']['from'];
          $to = ($this->request->data['Mail']['to']);
          $subject = $this->request->data['Mail']['subject'];
          $message = $this->request->data['Mail']['message'];

                $Email->sender($from, 'TestName');
                $Email->from($from)
                    ->bcc($to)  
                    ->replyTo($from)
                    ->subject($subject)
                    ->send($message);



                    $this->Session->setFlash('On the way to recipient');
                    $this->redirect(array('action' => 'index'));

I have edited the Config/Email.php file inserting the MailGun API credentials etc.

What's possibly going on? Can you find out why this happens?

Thanks in advance!


Solution

  • (I was having the same errors you were)

    The BasicTransport didn't have the right "pre-processing" nor the appropriate response handling.

    I copied over the functionality from CurlTransport and it works for me now.

    Specifically, we needed:

        $post = array();
        $post_preprocess = array_merge(
            $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject')),
            array(
                'text' => $email->message(CakeEmail::MESSAGE_TEXT),
                'html' => $email->message(CakeEmail::MESSAGE_HTML)
            )
        );
        foreach ($post_preprocess as $k => $v) {
            if (! empty($v)) {
                $post[strtolower($k)] = $v;
            }
        }
    

    and then:

        $response = $http->post($url, $post, $request);
        if ($response === false) {
            throw new SocketException("Mailgun BasicTransport error, no response", 500);
        }
    
        $http_status = $response->code;
        if ($http_status != 200) {
            throw new SocketException("Mailgun request failed.  Status: $http_status, Response: {$response->body}", 500);
        }