Refactor. Covered refactor in tests.

This commit is contained in:
Travis Swientek 2013-08-13 12:26:34 -07:00
parent 8498145b2f
commit 685a7351d5
16 changed files with 307 additions and 505 deletions

View File

@ -2,14 +2,16 @@ Mailgun-PHP
===========
[![Build Status](https://travis-ci.org/travelton/Mailgun-PHP.png?branch=master)](https://travis-ci.org/travelton/Mailgun-PHP)
This is the Mailgun PHP SDK. This SDK contains methods for easily interacting with the Mailgun API. Below are examples to get you started. For additional examples,
please see our SDK documentation at http://documentation.mailgun.com
This is the Mailgun PHP SDK. This SDK contains methods for easily interacting with the Mailgun API.
Below are examples to get you started. For additional examples, please see our official documentation
at http://documentation.mailgun.com
Current Release: 0.4-Beta
Installation
------------
To install the SDK, you will need to be using Composer in your project. If you aren't using Composer yet, it's really simple! Here's how to install composer and the Mailgun SDK.
To install the SDK, you will need to be using [Composer](http://getcomposer.org/) in your project.
If you aren't using Composer yet, it's really simple! Here's how to install composer and the Mailgun SDK.
```PHP
# Install Composer
@ -32,9 +34,7 @@ use Mailgun\Mailgun;
Usage
-----
Using the SDK should feel simple, if you're already familiar with our API endpoints. If not, no problem... When you're reviewing our documentation, use the provided resource URL when creating the HTTP request.
For example, here's how to use the "Messages" API endpoint:
Here's how to send a message using the SDK:
```php
# First, instantiate the SDK with your API credentials and define your domain.
@ -48,10 +48,25 @@ $mg->post('{$domain}/messages', array('from' => 'bob@example.com',
'text' => 'It is so simple to send a message.'));
```
Or obtain the last 25 log items:
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";
# Now, issue a GET against the Logs endpoint.
$mg->get('{$domain}/log', array('limit' => 'bob@example.com',
'skip' => 'sally@example.com');
```
For usage examples on each API endpoint, head over to our official documentation pages.
This SDK includes a [Message Builder](src/Mailgun/Messages/README.md) and [Batch Message](src/Mailgun/Messages/README.md) component.
Message Builder allows you to quickly create the array of parameters, required to send a message, by calling a methods for each parameter.
Batch Message is an extension of Message Builder, and allows you to easily send a batch message job within a few seconds. The complexity of
batch messaging is eliminated!
Support and Feedback
--------------------

View File

@ -2,8 +2,6 @@
namespace Mailgun\Connection;
require dirname(__DIR__) . '/Globals.php';
use Guzzle\Http\Client as Guzzle;
use Mailgun\MailgunClient;
@ -13,24 +11,32 @@ use Mailgun\Connection\Exceptions\NoDomainsConfigured;
use Mailgun\Connection\Exceptions\MissingRequiredMIMEParameters;
use Mailgun\Connection\Exceptions\MissingEndpoint;
/*
This class is a wrapper for the Guzzle (HTTP Client Library).
*/
class RestClient{
private $apiKey;
protected $mgClient;
public function __construct($apiKey, $apiEndpoint){
public function __construct($apiKey, $apiEndpoint, $apiVersion){
$this->apiKey = $apiKey;
$this->mgClient = new Guzzle('https://' . $apiEndpoint . '/' . API_VERSION . '/');
$this->mgClient = new Guzzle('https://' . $apiEndpoint . '/' . $apiVersion . '/');
$this->mgClient->setDefaultOption('curl.options', array('CURLOPT_FORBID_REUSE' => true));
$this->mgClient->setDefaultOption('auth', array (API_USER, $this->apiKey));
$this->mgClient->setDefaultOption('exceptions', false);
$this->mgClient->setUserAgent(SDK_USER_AGENT . '/' . SDK_VERSION);
}
public function postRequest($endpointUrl, $postData = array(), $files = array()){
public function post($endpointUrl, $postData = array(), $files = array()){
$request = $this->mgClient->post($endpointUrl, array(), $postData);
if(isset($files["message"])){
foreach($files as $message){
$request->addPostFile("message", $message);
}
}
if(isset($files["attachment"])){
foreach($files["attachment"] as $attachment){
$request->addPostFile("attachment", $attachment);
@ -46,7 +52,7 @@ class RestClient{
return $this->responseHandler($response);
}
public function getRequest($endpointUrl, $queryString = array()){
public function get($endpointUrl, $queryString = array()){
$request = $this->mgClient->get($endpointUrl);
if(isset($queryString)){
foreach($queryString as $key=>$value){
@ -57,13 +63,13 @@ class RestClient{
return $this->responseHandler($response);
}
public function deleteRequest($endpointUrl){
public function delete($endpointUrl){
$request = $this->mgClient->delete($endpointUrl);
$response = $request->send();
return $this->responseHandler($response);
}
public function putRequest($endpointUrl, $putData){
public function put($endpointUrl, $putData){
$request = $this->mgClient->put($endpointUrl, array(), $putData);
$response = $request->send();
return $this->responseHandler($response);
@ -93,7 +99,6 @@ class RestClient{
}
else{
throw new GenericHTTPError(EXCEPTION_GENERIC_HTTP_ERROR);
return false;
}
$result->http_response_code = $httpResponeCode;
return $result;

View File

@ -0,0 +1,24 @@
<?PHP
const API_USER = "api";
const SDK_VERSION = "0.1";
const SDK_USER_AGENT = "mailgun-sdk-php";
const RECIPIENT_COUNT_LIMIT = 1000;
const CAMPAIGN_ID_LIMIT = 3;
const TAG_LIMIT = 3;
//Common Exception Messages
const EXCEPTION_INVALID_CREDENTIALS = "Your credentials are incorrect.";
const EXCEPTION_GENERIC_HTTP_ERROR = "An HTTP Error has occurred! Check your network connection and try again.";
const EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS = "The parameters passed to the API were invalid. This might be a bug! Notify support@mailgun.com.";
const EXCEPTION_MISSING_ENDPOINT = "The endpoint you've tried to access does not exist. This might be a bug! Notify support@mailgun.com.";
const TOO_MANY_RECIPIENTS = "You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.";
const INVALID_PARAMETER_NON_ARRAY = "The parameter you've passed in position 2 must be an array.";
const INVALID_PARAMETER_ATTACHMENT = "Attachments must be passed with an \"@\" preceding the file path. Web resources not supported.";
const INVALID_PARAMETER_INLINE = "Inline images must be passed with an \"@\" preceding the file path. Web resources not supported.";
const TOO_MANY_PARAMETERS_CAMPAIGNS = "You've exceeded the maximum (3) campaigns for a single message.";
const TOO_MANY_PARAMETERS_TAGS = "You've exceeded the maximum (3) tags for a single message.";
const TOO_MANY_PARAMETERS_RECIPIENT = "You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.";
?>

View File

@ -2,36 +2,73 @@
namespace Mailgun;
use Mailgun\Connection\RestClient;
require 'Constants/Constants.php';
use Mailgun\Messages\Messages;
use Mailgun\Connection\Exceptions;
use Mailgun\Connection\RestClient;
use Mailgun\Messages\BatchMessage;
use Mailgun\Messages\MessageBuilder;
/*
This class is the base class for the Mailgun SDK.
See the official documentation for usage instructions.
*/
class Mailgun{
private $apiKey;
protected $workingDomain;
protected $restClient;
public function __construct($apiKey = null, $apiEndpoint = "api.mailgun.net"){
$this->restClient = new RestClient($apiKey, $apiEndpoint);
public function __construct($apiKey = null, $apiEndpoint = "api.mailgun.net", $apiVersion = "v2"){
$this->restClient = new RestClient($apiKey, $apiEndpoint, $apiVersion);
}
public function sendMessage($workingDomain, $postData, $postFiles = array()){
/*
This function allows the sending of a fully formed message OR a custom
MIME string. If sending MIME, the string must be passed in to the 3rd
position of the function call.
*/
if(is_array($postFiles)){
return $this->post("$workingDomain/messages", $postData, $postFiles);
}
else if(is_string($postFiles)){
try{
$tempFile = tempnam(sys_get_temp_dir(), "MG_TMP_MIME");
$fileHandle = fopen($tempFile, "w");
fwrite($fileHandle, $postFiles);
}
catch(Exception $ex){
throw $ex;
}
$result = $this->post("$workingDomain/messages.mime", $postData, array("message" => $tempFile));
return $result;
fclose($fileName);
unlink($fileName);
}
else{
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
}
public function post($endpointUrl, $postData = array(), $files = array()){
return $this->restClient->postRequest($endpointUrl, $postData, $files);
return $this->restClient->post($endpointUrl, $postData, $files);
}
public function get($endpointUrl, $queryString = array()){
return $this->restClient->getRequest($endpointUrl, $queryString);
return $this->restClient->get($endpointUrl, $queryString);
}
public function delete($endpointUrl){
return $this->restClient->getRequest($endpointUrl);
return $this->restClient->delete($endpointUrl);
}
public function put($endpointUrl, $putData){
return $this->restClient->putRequest($endpointUrl, $putData);
return $this->restClient->put($endpointUrl, $putData);
}
public function MessageBuilder(){

View File

@ -6,13 +6,17 @@ use Mailgun\Messages\MessageBuilder;
use Mailgun\Messages\Exceptions\TooManyParameters;
use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
/*
This class is used for batch sending. See the official documentation
for usage instructions.
*/
class BatchMessage extends MessageBuilder{
protected $batchRecipientAttributes;
protected $autoSend;
protected $restClient;
protected $workingDomain;
private $batchRecipientAttributes;
private $autoSend;
private $restClient;
private $workingDomain;
public function __construct($restClient, $workingDomain, $autoSend){
$this->batchRecipientAttributes = array();
@ -22,36 +26,18 @@ class BatchMessage extends MessageBuilder{
$this->endpointUrl = $workingDomain . "/messages";
}
public function addToRecipient($address, $attributes){
//Check for maximum recipient count
if($this->toRecipientCount == 1000){
//If autoSend is off, do things here.
public function addToRecipient($address, $variables){
if($this->toRecipientCount == RECIPIENT_COUNT_LIMIT){
if($this->autoSend == false){
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.");
throw new TooManyParameters(TOO_MANY_RECIPIENTS);
}
else{
$this->sendMessage();
}
}
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
$compiledAddress = $name . " <" . $address . ">";
if(isset($this->message["to"])){
array_push($this->message["to"], $compiledAddress);
}
else{
$this->message["to"] = array($compiledAddress);
}
$this->addRecipient("to", $address, $variables);
$attributes["id"] = $this->toRecipientCount;
$this->batchRecipientAttributes["$address"] = $attributes;
$this->batchRecipientAttributes["$address"] = $variables;
$this->toRecipientCount++;
return true;
}
public function sendMessage($message = array(), $files = array()){
@ -60,26 +46,27 @@ class BatchMessage extends MessageBuilder{
$files = $this->files;
}
if(!array_key_exists("from", $message)){
throw new MissingRequiredMIMEParameters("You are missing the from parameter for your message.");
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
elseif(!array_key_exists("to", $message)){
throw new MissingRequiredMIMEParameters("You are missing a recipient for your message.");
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
elseif(!array_key_exists("subject", $message)){
throw new MissingRequiredMIMEParameters("You are missing the subject of the message.");
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
elseif((!array_key_exists("text", $message) && !array_key_exists("html", $message))){
throw new MissingRequiredMIMEParameters("You are missing the body of the message.");
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
}
else{
$this->message["recipient-variables"] = json_encode($this->batchRecipientAttributes);
$response = $this->restClient->postRequest($this->endpointUrl, $message, $files);
$response = $this->restClient->post($this->endpointUrl, $message, $files);
$this->batchRecipientAttributes = array();
$this->toRecipientCount = 0;
unset($this->message["to"]);
return $response;
}
}
public function finalize(){
return $this->sendMessage();
}

View File

@ -6,9 +6,17 @@ use Mailgun\Messages\Expcetions\InvalidParameter;
use Mailgun\Messages\Exceptions\TooManyParameters;
use Mailgun\Messages\Expcetions\InvalidParameterType;
/*
This class is used for composing a properly formed
message object. Dealing with arrays can be cumbersome,
this class makes the process easier. See the official
documentation for usage instructions.
*/
class MessageBuilder{
protected $message = array();
protected $variables = array();
protected $files = array();
protected $sanitized;
protected $toRecipientCount = 0;
@ -19,123 +27,74 @@ class MessageBuilder{
protected $customOptionCount = 0;
protected $tagCount = 0;
public function __get($name){
return $this->message;
protected function safeGet($params, $key, $default){
if(array_key_exists($key, $params)){
return $params[$key];
}
return $default;
}
public function addToRecipient($address, $attributes){
if($this->toRecipientCount < 1000){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
protected function getFullName($params){
if(array_key_exists("first", $params)){
$first = $this->safeGet($params, "first", "");
$last = $this->safeGet($params, "last", "");
return trim("$first $last");
}
return $this->safeGet($params, "full_name", "");
}
protected function parseAddress($address, $variables){
if(!is_array($variables)){
return $address;
}
if(isset($name)){
$compiledAddress = $name . " <" . $address . ">";
$fullName = $this->getFullName($variables);
if($fullName != null){
return "'$fullName' <$address>";
}
return $baseAddress;
}
protected function addRecipient($headerName, $address, $variables){
if($headerName == "to" && $this->toRecipientCount > RECIPIENT_COUNT_LIMIT){
throw new TooManyParameters(TOO_MANY_PARAMETERS_RECIPIENT);
}
$compiledAddress = $this->parseAddress($address, $variables);
if(isset($this->message[$headerName])){
array_push($this->message[$headerName], $compiledAddress);
}
else{
$compiledAddress = $address;
}
if(isset($this->message["to"])){
array_push($this->message["to"], $compiledAddress);
}
else{
$this->message["to"] = array($compiledAddress);
$this->message[$headerName] = array($compiledAddress);
}
if($headerName == "to"){
$this->toRecipientCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the to field.");
}
}
public function addCcRecipient($address, $attributes){
if($this->ccRecipientCount < 1000){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
}
if(isset($name)){
$compiledAddress = $name . " <" . $address . ">";
}
else{
$compiledAddress = $address;
}
if(isset($this->message["cc"])){
array_push($this->message["cc"], $compiledAddress);
}
else{
$this->message["cc"] = array($compiledAddress);
}
$this->ccRecipientCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the cc field.");
}
public function addToRecipient($address, $variables = null){
$this->addRecipient("to", $address, $variables);
return end($this->message['to']);
}
public function addBccRecipient($address, $attributes){
if($this->bccRecipientCount < 1000){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
}
}
}
if(isset($name)){
$compiledAddress = $name . " <" . $address . ">";
}
else{
$compiledAddress = $address;
}
if(isset($this->message["bcc"])){
array_push($this->message["bcc"], $compiledAddress);
}
else{
$this->message["bcc"] = array($compiledAddress);
}
$this->bccRecipientCount++;
return true;
}
else{
throw new TooManyParameters("You've exceeded the maximum recipient count (1,000) on the bcc field.");
}
public function addCcRecipient($address, $variables = null){
$this->addRecipient("cc", $address, $variables);
return end($this->message['cc']);
}
public function setFromAddress($address, $attributes){
if(isset($attributes)){
if(is_array($attributes)){
if(array_key_exists("first", $attributes)){
$name = $attributes["first"];
if(array_key_exists("last", $attributes)){
$name = $attributes["first"] . " " . $attributes["last"];
public function addBccRecipient($address, $variables = null){
$this->addRecipient("bcc", $address, $variables);
return end($this->message['bcc']);
}
public function setFromAddress($address, $variables = null){
$this->addRecipient("from", $address, $variables);
return $this->message['from'];
}
}
else{
throw new InvalidParameterType("The parameter you've passed in position 2 must be an array.");
}
}
if(isset($name)){
$compiledAddress = $name . " <" . $address . ">";
}
else{
$compiledAddress = $address;
}
$this->message['from'] = $compiledAddress;
return true;
public function setReplyToAddress($address, $variables = null){
$this->addRecipient("h:reply-to", $address, $variables);
return $this->message['h:reply-to'];
}
public function setSubject($subject = NULL){
@ -143,7 +102,7 @@ class MessageBuilder{
$subject = " ";
}
$this->message['subject'] = $subject;
return true;
return $this->message['subject'];
}
public function addCustomHeader($headerName, $headerData){
@ -151,7 +110,7 @@ class MessageBuilder{
$headerName = "h:" . $headerName;
}
$this->message[$headerName] = array($headerData);
return true;
return $this->message[$headerName];
}
public function setTextBody($textBody){
@ -159,7 +118,7 @@ class MessageBuilder{
$textBody = " ";
}
$this->message['text'] = $textBody;
return true;
return $this->message['text'];
}
public function setHtmlBody($htmlBody){
@ -167,7 +126,7 @@ class MessageBuilder{
$htmlBody = " ";
}
$this->message['html'] = $htmlBody;
return true;
return $this->message['html'];
}
public function addAttachment($attachmentPath){
@ -181,7 +140,7 @@ class MessageBuilder{
return true;
}
else{
throw new InvalidParameter("Attachments must be passed with an \"@\" preceding the file path. Web resources not supported.");
throw new InvalidParameter(INVALID_PARAMETER_ATTACHMENT);
}
}
@ -197,7 +156,7 @@ class MessageBuilder{
}
}
else{
throw new InvalidParameter("Inline images must be passed with an \"@\" preceding the file path. Web resources not supported.");
throw new InvalidParameter(INVALID_PARAMETER_INLINE);
}
}
@ -209,11 +168,11 @@ class MessageBuilder{
$testMode = "no";
}
$this->message['o:testmode'] = $testMode;
return true;
return $this->message['o:testmode'];
}
public function addCampaignId($campaignId){
if($this->campaignIdCount < 3){
if($this->campaignIdCount < CAMPAIGN_ID_LIMIT){
if(isset($this->message['o:campaign'])){
array_push($this->message['o:campaign'] , $campaignId);
}
@ -221,15 +180,15 @@ class MessageBuilder{
$this->message['o:campaign'] = array($campaignId);
}
$this->campaignIdCount++;
return true;
return $this->message['o:campaign'];
}
else{
throw new TooManyParameters("You've exceeded the maximum (3) campaigns for a single message.");
throw new TooManyParameters(TOO_MANY_PARAMETERS_CAMPAIGNS);
}
}
public function addTag($tag){
if($this->tagCount < 3){
if($this->tagCount < TAG_LIMIT){
if(isset($this->message['o:tag'])){
array_push($this->message['o:tag'] , $tag);
}
@ -237,10 +196,10 @@ class MessageBuilder{
$this->message['o:tag'] = array($tag);
}
$this->tagCount++;
return true;
return $this->message['o:tag'];
}
else{
throw new TooManyParameters("You've exceeded the maximum (3) tags for a single message.");
throw new TooManyParameters(TOO_MANY_PARAMETERS_TAGS);
}
}
@ -252,7 +211,7 @@ class MessageBuilder{
$enabled = "no";
}
$this->message["o:dkim"] = $enabled;
return true;
return $this->message["o:dkim"];
}
public function setOpenTracking($enabled){
@ -263,18 +222,21 @@ class MessageBuilder{
$enabled = "no";
}
$this->message['o:tracking-opens'] = $enabled;
return true;
return $this->message['o:tracking-opens'];
}
public function setClickTracking($enabled){
if(filter_var($enabled, FILTER_VALIDATE_BOOLEAN)){
$enabled = "yes";
}
elseif($enabled == "html"){
$enabled = "html";
}
else{
$enabled = "no";
}
$this->message['o:tracking-clicks'] = $enabled;
return true;
return $this->message['o:tracking-clicks'];
}
public function setDeliveryTime($timeDate, $timeZone = NULL){
@ -288,51 +250,32 @@ class MessageBuilder{
$dateTimeObj = new \DateTime($timeDate, $timeZoneObj);
$formattedTimeDate = $dateTimeObj->format(\DateTime::RFC2822);
$this->message['o:deliverytime'] = $formattedTimeDate;
return true;
return $this->message['o:deliverytime'];
}
public function addCustomData($customName, $data){
if(is_array($data)){
$jsonArray = json_encode($data);
$this->message['v:'.$customName] = $jsonArray;
return $this->message['v:'.$customName];
}
else{
throw new InvalidParameter("Custom Data values must be passed as an array.");
return false;
throw new InvalidParameter(INVALID_PARAMETER_NON_ARRAY);
}
}
public function addCustomOption($optionName, $data){
if(!preg_match("/^o:/i", $optionName)){
$optionName = "o:" . $optionName;
}
if(isset($this->message['options'][$optionName])){
array_push($this->message['options'][$optionName], $data);
return true;
}
else{
$this->message['options'][$optionName] = array($data);
return true;
}
}
public function addCustomParameter($parameterName, $data){
if(isset($this->message[$parameterName])){
array_push($this->message[$parameterName], $data);
return true;
return $this->message[$parameterName];
}
else{
$this->message[$parameterName] = array($data);
return true;
return $this->message[$parameterName];
}
}
public function setMessage($message = array(), $files = array()){
$this->message = $message;
$this->files = $files;
}
public function getMessage(){
return $this->message;
}

View File

@ -1,58 +0,0 @@
<?php
namespace Mailgun\Messages;
use Mailgun\Messages\BatchMessage;
use Mailgun\Messages\MessageBuilder;
use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
class Messages{
protected $restClient;
protected $workingDomain;
protected $endpointUrl;
public function __construct($restClient){
$this->restClient = $restClient;
$this->workingDomain = $this->restClient->returnWorkingDomain();
$this->endpointUrl = $this->workingDomain . "/messages";
}
public function send($message = array(), $files = array()){
if(count($message) < 1){
$message = $this->message;
$files = $this->files;
}
if(!array_key_exists("from", $message)){
throw new MissingRequiredMIMEParameters("You are missing the from parameter for your message.");
}
elseif(!array_key_exists("to", $message)){
throw new MissingRequiredMIMEParameters("You are missing a recipient for your message.");
}
elseif(!array_key_exists("subject", $message)){
throw new MissingRequiredMIMEParameters("You are missing the subject of the message.");
}
elseif((!array_key_exists("text", $message) && !array_key_exists("html", $message))){
throw new MissingRequiredMIMEParameters("You are missing the body of the message.");
}
else{
$response = $this->restClient->postRequest($this->endpointUrl, $message, $files);
return $response;
}
}
public function setMessage($message = array(), $files = array()){
$this->message = $message;
$this->files = $files;
}
public function MessageBuilder(){
return new MessageBuilder($this->restClient);
}
public function BatchMessage($autoSend = true){
return new BatchMessage($this->restClient, $autoSend);
}
}
?>

View File

@ -1,129 +0,0 @@
Mailgun - Messages
====================
This is the Mailgun PHP *Message* utilities.
The below assumes you've already installed the Mailgun PHP SDK in to your project. If not, go back to the master README for instructions.
There are two utilities included, Message Builder and Batch Message.
Message Builder: Allows you to build a message object by calling methods for each MIME attribute.
Batch Message: Inherits Message Builder and allows you to iterate through recipients from a list. Messages will fire after the 1,000th recipient has been added.
Usage - Message Builder
-----------------------
Here's how to use Message Builder to build your Message.
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";
# Next, instantiate a Message Builder object from the SDK.
$messageBldr = $mg->MessageBuilder();
# Define the from address.
$messageBldr->setFromAddress("me@example.com", array("first"=>"PHP", "last" => "SDK"));
# Define a to recipient.
$messageBldr->addToRecipient("john.doe@example.com", array("first" => "John", "last" => "Doe"));
# Define a cc recipient.
$messageBldr->addCcRecipient("sally.doe@example.com", array("first" => "Sally", "last" => "Doe"));
# Define the subject.
$messageBldr->setSubject("A message from the PHP SDK using Message Builder!");
# Define the body of the message.
$messageBldr->setTextBody("This is the text body of the message!");
# Other Optional Parameters.
$messageBldr->addCampaignId("My-Awesome-Campaign");
$messageBldr->addCustomHeader("Customer-Id", "12345");
$messageBldr->addAttachment("@/tron.jpg");
$messageBldr->setDeliveryTime("tomorrow 8:00AM", "PST");
$messageBldr->setClickTracking(true);
# Finally, send the message.
$mg->post('{$domain}/messages', $messageBldr->getMessage());
```
Available Functions
-----------------------------------------------------
`addToRecipient(string $address, array $attributes)`
`addCcRecipient(string $address, array $attributes)`
`addBccRecipient(string $address, array $attributes)`
`setFromAddress(string $address, array $attributes)`
`setSubject(string $subject)`
`setTextBody(string $textBody)`
`setHtmlBody(string $htmlBody)`
`addAttachment(string $attachmentPath)`
`addInlineImage(string $inlineImagePath)`
`setTestMode(bool $testMode)`
`addCampaignId(string $campaignId)`
`setDkim(bool $enabled)`
`setOpenTracking($enabled)`
`setClickTracking($enabled)`
`setDeliveryTime(string $timeDate, string $timeZone)`
`addCustomOption(string $optionName, string $data)`
`addCustomParameter(string $parameterName, string $data)`
`setMessage(array $message, array $files)`
`getMessage()`
`getFiles()`
Usage - Batch Message
---------------------
Here's how to use Batch Message to easily handle batch sending jobs.
```php
# First, instantiate the SDK with your API credentials and define your domain.
$mg = new Mailgun("key-example");
$domain = "example.com";
# Next, instantiate a Message Builder object from the SDK, pass in your sending domain.
$batchMsg = $mg->BatchMessage($domain);
# Define the from address.
$batchMsg->setFromAddress("me@samples.mailgun.org", array("first"=>"PHP", "last" => "SDK"));
# Define the subject.
$batchMsg->setSubject("A Batch Message from the PHP SDK!");
# Define the body of the message.
$batchMsg->setTextBody("This is the text body of the message!");
# Next, let's add a few recipients to the batch job.
$batchMsg->addToRecipient("john.doe@samples.mailgun.org", array("first" => "John", "last" => "Doe"));
$batchMsg->addToRecipient("sally.doe@samples.mailgun.org", array("first" => "Sally", "last" => "Doe"));
$batchMsg->addToRecipient("mike.jones@samples.mailgun.org", array("first" => "Mike", "last" => "Jones"));
...
// After 1,000 recipeints, Batch Message will automatically post your message to the messages endpoint.
// Call finalize() to send any remaining recipients still in the buffer.
$batchMsg->finalize();
```
Available Functions (Inherits all Batch Message and Messages Functions)
-----------------------------------------------------------------------
`addToRecipient(string $address, string $attributes)`
More Documentation
------------------
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html) for more information.

View File

@ -1,16 +0,0 @@
<?PHP
class Test{
public function __call($name, $arguments){
return array($name => $arguments);
}
}
$test = new Test();
var_dump($test->olakwnfelkajweklfjlwkjelkmg("Asdfasdf"));
?>

View File

@ -1,12 +1,8 @@
<?PHP
const API_VERSION = "v2";
const API_ENDPOINT = "api.mailgun.net";
const API_USER = "api";
const SDK_VERSION = "0.1";
const SDK_USER_AGENT = "mailgun-sdk-php";
const DEFAULT_TIME_ZONE = "UTC";
//Common Exception Messages

View File

@ -7,91 +7,25 @@ class TestBroker extends RestClient{
private $apiKey;
protected $apiEndpoint;
protected $apiVersion = API_VERSION;
protected $apiUser = API_USER;
protected $sdkVersion = SDK_VERSION;
protected $sdkUserAgent = SDK_USER_AGENT;
public function __construct($apiKey = null, $apiEndpoint = "api.mailgun.net"){
public function __construct($apiKey = null, $apiEndpoint = "api.mailgun.net", $apiVersion = "v2"){
$this->apiKey = $apiKey;
$this->apiEndpoint = $apiEndpoint;
}
public function postRequest($endpointUrl, $postData = array(), $files = array()){
if(preg_match("/\/messages$/", $endpointUrl)){
public function post($endpointUrl, $postData = array(), $files = array()){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/unsubscribes$/", $endpointUrl)){
public function get($endpointUrl, $queryString = array()){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/complaints$/", $endpointUrl)){
public function delete($endpointUrl){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/bounces$/", $endpointUrl)){
public function put($endpointUrl, $queryString){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
else{
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
return $result;
}
public function getRequest($endpointUrl, $queryString = array()){
if($endpointUrl == "domains"){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/unsubscribes\//", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/unsubscribes/", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/complaints/", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/bounces/", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/stats/", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/log/", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
else{
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
return $result;
}
public function deleteRequest($endpointUrl){
if($endpointUrl == "domains"){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/unsubscribes\//", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/complaints\//", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/bounces\//", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
elseif(preg_match("/\/tags\//", $endpointUrl)){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
else{
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
return $result;
}
public function putRequest($endpointUrl, $queryString){
if($endpointUrl == "domains"){
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
else{
return $this->responseHandler($endpointUrl, $httpResponseCode = 200);
}
return $result;
}
public function responseHandler($endpointUrl, $httpResponseCode = 200){
if($httpResponseCode === 200){
$result = new \stdClass();
@ -118,6 +52,7 @@ class TestBroker extends RestClient{
return false;
}
$result->http_response_code = $httpResponseCode;
$result->http_endpoint_url = $endpointUrl;
return $result;
}

View File

@ -2,6 +2,9 @@
namespace Mailgun\Tests;
require 'Connection/Constants/Constants.php';
require 'Messages/Constants/Constants.php';
use Mailgun\Mailgun;
use Mailgun\Tests\Connection\TestBroker;
@ -10,9 +13,8 @@ class MailgunTest extends Mailgun
protected $debug;
protected $restClient;
public function __construct($apiKey = null, $apiEndpoint = "api.mailgun.net"){
$this->restClient = new TestBroker($apiKey, $apiEndpoint);
return true;
public function __construct($apiKey = null, $apiEndpoint = "api.mailgun.net", $apiVersion = "v2"){
$this->restClient = new TestBroker($apiKey, $apiEndpoint, $apiVersion);
}
}

View File

@ -1,5 +1,5 @@
<?PHP
namespace Mailgun\Tests\BatchMessage;
namespace Mailgun\Tests\Messages;
use Mailgun\Tests\MailgunTest;
@ -19,7 +19,7 @@ class BatchMessageTest extends \Mailgun\Tests\MailgunTestCase{
$message = $this->client->BatchMessage($this->sampleDomain);
$message->addToRecipient("test@samples.mailgun.org", array("first" => "Test", "last" => "User"));
$messageObj= $message->getMessage();
$this->assertEquals(array("to" => array("Test User <test@samples.mailgun.org>")), $messageObj);
$this->assertEquals(array("to" => array("'Test User' <test@samples.mailgun.org>")), $messageObj);
}
public function testAddMultipleBatchRecipients(){
$message = $this->client->BatchMessage($this->sampleDomain);

View File

@ -0,0 +1,21 @@
<?PHP
const RECIPIENT_COUNT_LIMIT = 1000;
const CAMPAIGN_ID_LIMIT = 3;
const TAG_LIMIT = 3;
//Common Exception Messages
const TOO_MANY_RECIPIENTS = "You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.";
const EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS = "The parameters passed to the API were invalid. This might be a bug! Notify support@mailgun.com.";
const INVALID_PARAMETER_NON_ARRAY = "The parameter you've passed in position 2 must be an array.";
const INVALID_PARAMETER_ATTACHMENT = "Attachments must be passed with an \"@\" preceding the file path. Web resources not supported.";
const INVALID_PARAMETER_INLINE = "Inline images must be passed with an \"@\" preceding the file path. Web resources not supported.";
const TOO_MANY_PARAMETERS_CAMPAIGNS = "You've exceeded the maximum (3) campaigns for a single message.";
const TOO_MANY_PARAMETERS_TAGS = "You've exceeded the maximum (3) tags for a single message.";
const TOO_MANY_PARAMETERS_RECIPIENT = "You've exceeded the maximum recipient count (1,000) on the to field with autosend disabled.";
?>

View File

@ -1,5 +1,5 @@
<?PHP
namespace Mailgun\Tests\Message;
namespace Mailgun\Tests\Messages;
use Mailgun\Tests\MailgunTest;
@ -18,25 +18,25 @@ class MessageBuilderTest extends \Mailgun\Tests\MailgunTestCase{
$message = $this->client->MessageBuilder();
$message->addToRecipient("test@samples.mailgun.org", array("first" => "Test", "last" => "User"));
$messageObj = $message->getMessage();
$this->assertEquals(array("to" => array("Test User <test@samples.mailgun.org>")), $messageObj);
$this->assertEquals(array("to" => array("'Test User' <test@samples.mailgun.org>")), $messageObj);
}
public function testAddCcRecipient(){
$message = $this->client->MessageBuilder();
$message->addCcRecipient("test@samples.mailgun.org", array("first" => "Test", "last" => "User"));
$messageObj = $message->getMessage();
$this->assertEquals(array("cc" => array("Test User <test@samples.mailgun.org>")), $messageObj);
$this->assertEquals(array("cc" => array("'Test User' <test@samples.mailgun.org>")), $messageObj);
}
public function testAddBccRecipient(){
$message = $this->client->MessageBuilder();
$message->addBccRecipient("test@samples.mailgun.org", array("first" => "Test", "last" => "User"));
$messageObj = $message->getMessage();
$this->assertEquals(array("bcc" => array("Test User <test@samples.mailgun.org>")), $messageObj);
$this->assertEquals(array("bcc" => array("'Test User' <test@samples.mailgun.org>")), $messageObj);
}
public function testSetFromAddress(){
$message = $this->client->MessageBuilder();
$message->setFromAddress("test@samples.mailgun.org", array("first" => "Test", "last" => "User"));
$messageObj = $message->getMessage();
$this->assertEquals(array("from" => "Test User <test@samples.mailgun.org>"), $messageObj);
$this->assertEquals(array("from" => array("'Test User' <test@samples.mailgun.org>")), $messageObj);
}
public function testSetSubject(){
$message = $this->client->MessageBuilder();
@ -166,12 +166,12 @@ class MessageBuilderTest extends \Mailgun\Tests\MailgunTestCase{
$messageObj = $message->getMessage();
$this->assertEquals(array("v:My-Super-Awesome-Data" => "{\"What\":\"Mailgun Rocks!\"}"), $messageObj);
}
public function testAddCustomOption(){
public function testAddCustomParameter(){
$message = $this->client->MessageBuilder();
$message->addCustomOption("my-option", "yes");
$message->addCustomOption("o:my-other-option", "no");
$message->addCustomParameter("my-option", "yes");
$message->addCustomParameter("o:my-other-option", "no");
$messageObj = $message->getMessage();
$this->assertEquals(array("options" => array("o:my-option" => array("yes"), "o:my-other-option" => array("no"))), $messageObj);
$this->assertEquals(array("my-option" => array("yes"), "o:my-other-option" => array("no")), $messageObj);
}
}

View File

@ -0,0 +1,40 @@
<?PHP
namespace Mailgun\Tests\Messages;
use Mailgun\Tests\MailgunTest;
class StandardMessageTest extends \Mailgun\Tests\MailgunTestCase{
private $client;
private $sampleDomain = "samples.mailgun.org";
public function setUp(){
$this->client = new MailgunTest("My-Super-Awesome-API-Key");
}
public function testSendMIMEMessage(){
$customMime = "Received: by luna.mailgun.net with SMTP mgrt 8728174999085; Mon, 10 Jun 2013 09:50:58 +0000
Mime-Version: 1.0
Content-Type: text/plain; charset=\"ascii\"
Subject: This is the Subject!
From: Mailgun Testing <test@test.mailgun.com>
To: test@test.mailgun.com
Message-Id: <20130610095049.30790.4334@test.mailgun.com>
Content-Transfer-Encoding: 7bit
X-Mailgun-Sid: WyIxYTdhMyIsICJmaXplcmtoYW5AcXVhZG1zLmluIiwgImExOWQiXQ==
Date: Mon, 10 Jun 2013 09:50:58 +0000
Sender: test@test.mailgun.com
Mailgun is testing!";
$envelopeFields = array('to' => 'test@test.mailgun.org');
$result = $this->client->sendMessage("test.mailgun.org", $envelopeFields, $customMime);
$this->assertEquals("test.mailgun.org/messages.mime", $result->http_endpoint_url);
}
public function testSendMessage(){
$message = array('to' => 'test@test.mailgun.org', 'from' => 'sender@test.mailgun.org', 'subject' => 'This is my test subject', 'text' => 'Testing!');
$result = $this->client->sendMessage("test.mailgun.org", $message);
$this->assertEquals("test.mailgun.org/messages", $result->http_endpoint_url);
}
}
?>