Skip to content

Instantly share code, notes, and snippets.

@fenixkim
Created July 24, 2016 16:27
Show Gist options
  • Save fenixkim/b38bf35684cac448b631abc5ecf63430 to your computer and use it in GitHub Desktop.
Save fenixkim/b38bf35684cac448b631abc5ecf63430 to your computer and use it in GitHub Desktop.
Kirby Custom Mailgun Email Service
<?php
// Put this file in the Plugins folder
email::$services['mailgun'] = function($email) {
if(empty($email->options['key'])) throw new Error('Missing Mailgun API key');
if(empty($email->options['domain'])) throw new Error('Missing Mailgun API domain');
$url = 'https://api.mailgun.net/v3/' . $email->options['domain'] . '/messages';
//$auth = base64_encode('api:' . $email->options['key']);
$auth = 'api:' . $email->options['key'];
$headers = array(
//'Content-Type: application/json',
'Accept: application/json',
'Authorization: Basic ' . $auth
);
$data = array(
'from' => $email->from,
'to' => $email->to,
'subject' => $email->subject,
'text' => $email->body,
'h:Reply-To' => $email->replyTo,
);
if($email->html()) $data['html'] = $email->html;
// This method doesn't work on production servers
/*
$email->response = remote::post($url, array(
'data' => $data,
'headers' => $headers,
'method' => 'POST',
));
*/
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $auth);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
//$json = json_decode($result);
$info = curl_getinfo($curl);
curl_close($curl);
// TODO Set the email resonse method
//$email->response
if($info['http_code'] != 200) {
throw new Error('The mail could not be sent!');
}
};
<?php
$email = new Email(array(
'to' => '[email protected]',
'from' => 'Excited User <mailgun@YOUR_DOMAIN_NAME>',
//'replyTo' => [email protected], // Recommended
'subject' => 'Hello',
'body' => 'Testing some Mailgun awesomness!',
'service' => 'mailgun',
'options' => array(
'domain' => 'YOUR_DOMAIN_NAME',
'key' => 'YOUR_API_KEY',
)
));
if ($email->send()) {
$success = l('contact.success');
$requestData = array();
} else {
$alert = l('contact.error');
$success = false;
}
@fenixkim
Copy link
Author

For any reason I can't make work the official Kirby CMS Mailgun email service in production servers. This works fine in localhost but in production doesn't works. Maybe is something about my server configuration.

I fix this issue avoiding the use of the remote:post method and making a custom CURL call

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment