mirror of
https://github.com/retailcrm/mailgun-php.git
synced 2024-11-29 00:25:37 +03:00
Removed deprecated code (#521)
* Removed deprecated code * cs * Removed more deprecated code * minor
This commit is contained in:
parent
12fee2f714
commit
e341a44a5c
@ -1,40 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Connection\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class GenericHTTPError extends \Exception implements Exception
|
||||
{
|
||||
protected $httpResponseCode;
|
||||
|
||||
protected $httpResponseBody;
|
||||
|
||||
public function __construct($message = null, $response_code = null, $response_body = null, $code = 0, \Exception $previous = null)
|
||||
{
|
||||
parent::__construct($message, $code, $previous);
|
||||
|
||||
$this->httpResponseCode = $response_code;
|
||||
$this->httpResponseBody = $response_body;
|
||||
}
|
||||
|
||||
public function getHttpResponseCode()
|
||||
{
|
||||
return $this->httpResponseCode;
|
||||
}
|
||||
|
||||
public function getHttpResponseBody()
|
||||
{
|
||||
return $this->httpResponseBody;
|
||||
}
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Connection\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class InvalidCredentials extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Connection\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class MissingEndpoint extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Connection\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class MissingRequiredParameters extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Connection\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class NoDomainsConfigured extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,379 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Connection;
|
||||
|
||||
use Http\Client\HttpClient;
|
||||
use Http\Discovery\HttpClientDiscovery;
|
||||
use Http\Discovery\MessageFactoryDiscovery;
|
||||
use Http\Message\MultipartStream\MultipartStreamBuilder;
|
||||
use Mailgun\Connection\Exceptions\GenericHTTPError;
|
||||
use Mailgun\Connection\Exceptions\InvalidCredentials;
|
||||
use Mailgun\Connection\Exceptions\MissingEndpoint;
|
||||
use Mailgun\Connection\Exceptions\MissingRequiredParameters;
|
||||
use Mailgun\Constants\Api;
|
||||
use Mailgun\Constants\ExceptionMessages;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* This class is a wrapper for the HTTP client.
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class RestClient
|
||||
{
|
||||
/**
|
||||
* Your API key.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $apiKey;
|
||||
|
||||
/**
|
||||
* @var HttpClient
|
||||
*/
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $apiHost;
|
||||
|
||||
/**
|
||||
* The version of the API to use.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $apiVersion = 'v2';
|
||||
|
||||
/**
|
||||
* If we should use SSL or not.
|
||||
*
|
||||
* @var bool
|
||||
*
|
||||
* @deprecated To be removed in 3.0
|
||||
*/
|
||||
protected $sslEnabled = true;
|
||||
|
||||
/**
|
||||
* @param string $apiKey
|
||||
* @param string $apiHost
|
||||
* @param HttpClient $httpClient
|
||||
*/
|
||||
public function __construct($apiKey, $apiHost, HttpClient $httpClient = null)
|
||||
{
|
||||
$this->apiKey = $apiKey;
|
||||
$this->apiHost = $apiHost;
|
||||
$this->httpClient = $httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $method
|
||||
* @param string $uri
|
||||
* @param mixed $body
|
||||
* @param array $files
|
||||
* @param array $headers
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
protected function send($method, $uri, $body = null, $files = [], array $headers = [])
|
||||
{
|
||||
$headers['User-Agent'] = Api::SDK_USER_AGENT.'/'.Api::SDK_VERSION;
|
||||
$headers['Authorization'] = 'Basic '.base64_encode(sprintf('%s:%s', Api::API_USER, $this->apiKey));
|
||||
|
||||
if (!empty($files)) {
|
||||
$builder = new MultipartStreamBuilder();
|
||||
foreach ($files as $file) {
|
||||
$builder->addResource($file['name'], $file['contents'], $file);
|
||||
}
|
||||
$body = $builder->build();
|
||||
$headers['Content-Type'] = 'multipart/form-data; boundary="'.$builder->getBoundary().'"';
|
||||
} elseif (is_array($body)) {
|
||||
$body = http_build_query($body);
|
||||
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
}
|
||||
|
||||
$request = MessageFactoryDiscovery::find()->createRequest($method, $this->getApiUrl($uri), $headers, $body);
|
||||
$response = $this->getHttpClient()->sendRequest($request);
|
||||
|
||||
return $this->responseHandler($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $url
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function getAttachment($url)
|
||||
{
|
||||
$headers['User-Agent'] = Api::SDK_USER_AGENT.'/'.Api::SDK_VERSION;
|
||||
$headers['Authorization'] = 'Basic '.base64_encode(sprintf('%s:%s', Api::API_USER, $this->apiKey));
|
||||
$request = MessageFactoryDiscovery::find()->createRequest('get', $url, $headers);
|
||||
$response = HttpClientDiscovery::find()->sendRequest($request);
|
||||
|
||||
return $this->responseHandler($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
* @param array $postData
|
||||
* @param array $files
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function post($endpointUrl, array $postData = [], $files = [])
|
||||
{
|
||||
$postFiles = [];
|
||||
|
||||
$fields = ['message', 'attachment', 'inline'];
|
||||
foreach ($fields as $fieldName) {
|
||||
if (isset($files[$fieldName])) {
|
||||
if (is_array($files[$fieldName])) {
|
||||
foreach ($files[$fieldName] as $file) {
|
||||
$postFiles[] = $this->prepareFile($fieldName, $file);
|
||||
}
|
||||
} else {
|
||||
$postFiles[] = $this->prepareFile($fieldName, $files[$fieldName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$postDataMultipart = [];
|
||||
foreach ($postData as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
foreach ($value as $subValue) {
|
||||
$postDataMultipart[] = [
|
||||
'name' => $key,
|
||||
'contents' => $subValue,
|
||||
];
|
||||
}
|
||||
} else {
|
||||
$postDataMultipart[] = [
|
||||
'name' => $key,
|
||||
'contents' => $value,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->send('POST', $endpointUrl, [], array_merge($postDataMultipart, $postFiles));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
* @param array $queryString
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function get($endpointUrl, $queryString = [])
|
||||
{
|
||||
return $this->send('GET', $endpointUrl.'?'.http_build_query($queryString));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function delete($endpointUrl)
|
||||
{
|
||||
return $this->send('DELETE', $endpointUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
* @param mixed $putData
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function put($endpointUrl, $putData)
|
||||
{
|
||||
return $this->send('PUT', $endpointUrl, $putData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ResponseInterface $responseObj
|
||||
*
|
||||
* @throws GenericHTTPError
|
||||
* @throws InvalidCredentials
|
||||
* @throws MissingEndpoint
|
||||
* @throws MissingRequiredParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function responseHandler(ResponseInterface $responseObj)
|
||||
{
|
||||
$httpResponseCode = (int) $responseObj->getStatusCode();
|
||||
|
||||
switch ($httpResponseCode) {
|
||||
case 200:
|
||||
$data = (string) $responseObj->getBody();
|
||||
$jsonResponseData = json_decode($data, false);
|
||||
$result = new \stdClass();
|
||||
// return response data as json if possible, raw if not
|
||||
$result->http_response_body = $data && null === $jsonResponseData ? $data : $jsonResponseData;
|
||||
$result->http_response_code = $httpResponseCode;
|
||||
|
||||
return $result;
|
||||
case 400:
|
||||
throw new MissingRequiredParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_PARAMETERS.$this->getResponseExceptionMessage($responseObj));
|
||||
case 401:
|
||||
throw new InvalidCredentials(ExceptionMessages::EXCEPTION_INVALID_CREDENTIALS);
|
||||
case 404:
|
||||
throw new MissingEndpoint(ExceptionMessages::EXCEPTION_MISSING_ENDPOINT.$this->getResponseExceptionMessage($responseObj));
|
||||
default:
|
||||
throw new GenericHTTPError(ExceptionMessages::EXCEPTION_GENERIC_HTTP_ERROR, $httpResponseCode, $responseObj->getBody());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ResponseInterface $responseObj
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getResponseExceptionMessage(ResponseInterface $responseObj)
|
||||
{
|
||||
$body = (string) $responseObj->getBody();
|
||||
$response = json_decode($body);
|
||||
if (JSON_ERROR_NONE == json_last_error() && isset($response->message)) {
|
||||
return ' '.$response->message;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare a file for the postBody.
|
||||
*
|
||||
* @param string $fieldName
|
||||
* @param string|array $filePath
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function prepareFile($fieldName, $filePath)
|
||||
{
|
||||
$filename = null;
|
||||
|
||||
if (is_array($filePath) && isset($filePath['fileContent'])) {
|
||||
// File from memory
|
||||
$filename = $filePath['filename'];
|
||||
$resource = fopen('php://temp', 'r+');
|
||||
fwrite($resource, $filePath['fileContent']);
|
||||
rewind($resource);
|
||||
} else {
|
||||
// Backward compatibility code
|
||||
if (is_array($filePath) && isset($filePath['filePath'])) {
|
||||
$filename = $filePath['remoteName'];
|
||||
$filePath = $filePath['filePath'];
|
||||
}
|
||||
|
||||
// Remove leading @ symbol
|
||||
if (0 === strpos($filePath, '@')) {
|
||||
$filePath = substr($filePath, 1);
|
||||
}
|
||||
|
||||
$resource = fopen($filePath, 'r');
|
||||
}
|
||||
|
||||
return [
|
||||
'name' => $fieldName,
|
||||
'contents' => $resource,
|
||||
'filename' => $filename,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HttpClient
|
||||
*/
|
||||
protected function getHttpClient()
|
||||
{
|
||||
if (null === $this->httpClient) {
|
||||
$this->httpClient = HttpClientDiscovery::find();
|
||||
}
|
||||
|
||||
return $this->httpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $uri
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getApiUrl($uri)
|
||||
{
|
||||
return $this->generateEndpoint($this->apiHost, $this->apiVersion, $this->sslEnabled).$uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $apiEndpoint
|
||||
* @param string $apiVersion
|
||||
* @param bool $ssl
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function generateEndpoint($apiEndpoint, $apiVersion, $ssl)
|
||||
{
|
||||
return ($ssl ? 'https://' : 'http://').$apiEndpoint.'/'.$apiVersion.'/';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $apiVersion
|
||||
*
|
||||
* @return RestClient
|
||||
*/
|
||||
public function setApiVersion($apiVersion)
|
||||
{
|
||||
$this->apiVersion = $apiVersion;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $sslEnabled
|
||||
*
|
||||
* @return RestClient
|
||||
*
|
||||
* @deprecated To be removed in 3.0
|
||||
*/
|
||||
public function setSslEnabled($sslEnabled)
|
||||
{
|
||||
$this->sslEnabled = $sslEnabled;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Constants;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class Api
|
||||
{
|
||||
const API_USER = 'api';
|
||||
|
||||
const SDK_VERSION = '1.7';
|
||||
|
||||
const SDK_USER_AGENT = 'mailgun-sdk-php';
|
||||
|
||||
const RECIPIENT_COUNT_LIMIT = 1000;
|
||||
|
||||
const CAMPAIGN_ID_LIMIT = 3;
|
||||
|
||||
const TAG_LIMIT = 3;
|
||||
|
||||
const DEFAULT_TIME_ZONE = 'UTC';
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Constants;
|
||||
|
||||
/**
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
class ExceptionMessages
|
||||
{
|
||||
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_PARAMETERS = 'The parameters passed to the API were invalid. Check your inputs!';
|
||||
|
||||
const EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS = 'The parameters passed to the API were invalid. Check your inputs!';
|
||||
|
||||
const EXCEPTION_MISSING_ENDPOINT = "The endpoint you've tried to access does not exist. Check if the domain matches the domain you have configure on Mailgun.";
|
||||
|
||||
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.";
|
||||
}
|
@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Lists;
|
||||
|
||||
/**
|
||||
* This class is used for creating a unique hash for
|
||||
* mailing list subscription double-opt in requests.
|
||||
*
|
||||
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Lists/README.md
|
||||
*/
|
||||
class OptInHandler
|
||||
{
|
||||
/**
|
||||
* @param string $mailingList
|
||||
* @param string $secretAppId
|
||||
* @param string $recipientAddress
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function generateHash($mailingList, $secretAppId, $recipientAddress)
|
||||
{
|
||||
$innerPayload = ['r' => $recipientAddress, 'l' => $mailingList];
|
||||
$encodedInnerPayload = base64_encode(json_encode($innerPayload));
|
||||
|
||||
$innerHash = hash_hmac('sha1', $encodedInnerPayload, $secretAppId);
|
||||
$outerPayload = ['h' => $innerHash, 'p' => $encodedInnerPayload];
|
||||
|
||||
return urlencode(base64_encode(json_encode($outerPayload)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $secretAppId
|
||||
* @param string $uniqueHash
|
||||
*
|
||||
* @return array|bool
|
||||
*/
|
||||
public function validateHash($secretAppId, $uniqueHash)
|
||||
{
|
||||
$decodedOuterPayload = json_decode(base64_decode(urldecode($uniqueHash)), true);
|
||||
|
||||
$decodedHash = $decodedOuterPayload['h'];
|
||||
$innerPayload = $decodedOuterPayload['p'];
|
||||
|
||||
$decodedInnerPayload = json_decode(base64_decode($innerPayload), true);
|
||||
$computedInnerHash = hash_hmac('sha1', $innerPayload, $secretAppId);
|
||||
|
||||
if ($computedInnerHash == $decodedHash) {
|
||||
return ['recipientAddress' => $decodedInnerPayload['r'], 'mailingList' => $decodedInnerPayload['l']];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
@ -1,116 +0,0 @@
|
||||
Mailgun - Lists
|
||||
====================
|
||||
|
||||
This is the Mailgun PHP *Lists* 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 is currently one utility provided.
|
||||
|
||||
OptInHandler: Provides methods for authenticating an OptInRequest.
|
||||
|
||||
The typical flow for using this utility would be as follows:
|
||||
**Recipient Requests Subscribe** -> [Validate Recipient Address] -> [Generate Opt In Link] -> [Email Recipient Opt In Link]
|
||||
**Recipient Clicks Opt In Link** -> [Validate Opt In Link] -> [Subscribe User] -> [Send final confirmation]
|
||||
|
||||
The above flow is modeled below.
|
||||
|
||||
Usage - Opt-In Handler (Recipient Requests Subscribe)
|
||||
-----------------------------------------------------
|
||||
Here's how to use Opt-In Handler to validate Opt-In requests.
|
||||
|
||||
```php
|
||||
# First, instantiate the SDK with your API credentials, domain, and required parameters for example.
|
||||
$mg = new Mailgun('key-example');
|
||||
$mgValidate = new Mailgun('pub-key-example');
|
||||
|
||||
$domain = 'example.com';
|
||||
$mailingList = 'youlist@example.com';
|
||||
$secretPassphrase = 'a_secret_passphrase';
|
||||
$recipientAddress = 'recipient@example.com';
|
||||
|
||||
# Let's validate the customer's email address, using Mailgun's validation endpoint.
|
||||
$result = $mgValidate->get('address/validate', array('address' => $recipientAddress));
|
||||
|
||||
if($result->http_response_body->is_valid == true){
|
||||
# Next, instantiate an OptInHandler object from the SDK.
|
||||
$optInHandler = $mg->OptInHandler();
|
||||
|
||||
# Next, generate a hash.
|
||||
$generatedHash = $optInHandler->generateHash($mailingList, $secretPassphrase, $recipientAddress);
|
||||
|
||||
# Now, let's send a confirmation to the recipient with our link.
|
||||
$mg->sendMessage($domain, array('from' => 'bob@example.com',
|
||||
'to' => $recipientAddress,
|
||||
'subject' => 'Please Confirm!',
|
||||
'html' => "<html><body>Hello,<br><br>You have requested to be subscribed
|
||||
to the mailing list $mailingList. Please <a
|
||||
href=\"http://yourdomain.com/subscribe.php?hash=$generatedHash\">
|
||||
confirm</a> your subscription.<br><br>Thank you!</body></html>"));
|
||||
|
||||
# Finally, let's add the subscriber to a Mailing List, as unsubscribed, so we can track non-conversions.
|
||||
$mg->post("lists/$mailingList/members", array('address' => $recipientAddress,
|
||||
'subscribed' => 'no',
|
||||
'upsert' => 'yes'));
|
||||
}
|
||||
```
|
||||
|
||||
Usage - Opt-In Handler (Recipient Clicks Opt In Link)
|
||||
-----------------------------------------------------
|
||||
Here's how to use Opt-In Handler to validate an Opt-In Hash.
|
||||
|
||||
```php
|
||||
# First, instantiate the SDK with your API credentials and domain.
|
||||
$mg = new Mailgun('key-example');
|
||||
$domain = 'example.com';
|
||||
|
||||
# Next, instantiate an OptInHandler object from the SDK.
|
||||
$optInHandler = $mg->OptInHandler();
|
||||
|
||||
# Next, grab the hash.
|
||||
$inboundHash = $_GET['hash'];
|
||||
$secretPassphrase = 'a_secret_passphrase';
|
||||
|
||||
# Now, validate the captured hash.
|
||||
$hashValidation = $optInHandler->validateHash($secretPassphrase, $inboundHash);
|
||||
|
||||
# Lastly, check to see if we have results, parse, subscribe, and send confirmation.
|
||||
if($hashValidation){
|
||||
$validatedList = $hashValidation['mailingList'];
|
||||
$validatedRecipient = $hashValidation['recipientAddress'];
|
||||
|
||||
$mg->put("lists/$validatedList/members/$validatedRecipient",
|
||||
array('address' => $validatedRecipient,
|
||||
'subscribed' => 'yes'));
|
||||
|
||||
$mg->sendMessage($domain, array('from' => 'bob@example.com',
|
||||
'to' => $validatedRecipient,
|
||||
'subject' => 'Confirmation Received!',
|
||||
'html' => "<html><body>Hello,<br><br>We've successfully subscribed
|
||||
you to the list, $validatedList!<br><br>Thank you!
|
||||
</body></html>"));
|
||||
}
|
||||
```
|
||||
|
||||
A few notes:
|
||||
1. 'a_secret_passphrase' can be anything. It's used as the *key* in hashing,
|
||||
since your email address will vary.
|
||||
2. validateHash() will return an array containing the recipient address and list
|
||||
address.
|
||||
3. You should *always* send an email confirmation before and after the
|
||||
subscription request.
|
||||
4. WARNING: On $_GET['hash'], you need to sanitize this value to prevent
|
||||
malicious attempts to inject code.
|
||||
|
||||
Available Functions
|
||||
-----------------------------------------------------
|
||||
|
||||
`string generateHash(string $mailingList, string $secretAppId, string $recipientAddress)`
|
||||
|
||||
`array validateHash(string $secretAppId, string $uniqueHash)`
|
||||
|
||||
More Documentation
|
||||
------------------
|
||||
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html)
|
||||
for more information.
|
261
src/Mailgun.php
261
src/Mailgun.php
@ -10,14 +10,7 @@
|
||||
namespace Mailgun;
|
||||
|
||||
use Http\Client\Common\HttpMethodsClient;
|
||||
use Http\Client\HttpClient;
|
||||
use Mailgun\Connection\RestClient;
|
||||
use Mailgun\Constants\ExceptionMessages;
|
||||
use Mailgun\HttpClient\Plugin\History;
|
||||
use Mailgun\Lists\OptInHandler;
|
||||
use Mailgun\Messages\BatchMessage;
|
||||
use Mailgun\Messages\Exceptions;
|
||||
use Mailgun\Messages\MessageBuilder;
|
||||
use Mailgun\Hydrator\ModelHydrator;
|
||||
use Mailgun\Hydrator\Hydrator;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
@ -25,19 +18,12 @@ use Psr\Http\Message\ResponseInterface;
|
||||
/**
|
||||
* This class is the base class for the Mailgun SDK.
|
||||
*/
|
||||
class Mailgun
|
||||
final class Mailgun
|
||||
{
|
||||
/**
|
||||
* @var RestClient
|
||||
*
|
||||
* @depracated Will be removed in 3.0
|
||||
*/
|
||||
protected $restClient;
|
||||
|
||||
/**
|
||||
* @var null|string
|
||||
*/
|
||||
protected $apiKey;
|
||||
private $apiKey;
|
||||
|
||||
/**
|
||||
* @var HttpMethodsClient
|
||||
@ -59,130 +45,28 @@ class Mailgun
|
||||
*
|
||||
* @var History
|
||||
*/
|
||||
private $responseHistory = null;
|
||||
private $responseHistory;
|
||||
|
||||
/**
|
||||
* @param string|null $apiKey
|
||||
* @param HttpClient|null $httpClient
|
||||
* @param string $apiEndpoint
|
||||
* @param Hydrator|null $hydrator
|
||||
* @param RequestBuilder|null $requestBuilder
|
||||
*
|
||||
* @internal Use Mailgun::configure or Mailgun::create instead.
|
||||
*/
|
||||
public function __construct(
|
||||
$apiKey = null, /* Deprecated, will be removed in 3.0 */
|
||||
HttpClient $httpClient = null,
|
||||
$apiEndpoint = 'api.mailgun.net', /* Deprecated, will be removed in 3.0 */
|
||||
Hydrator $hydrator = null,
|
||||
RequestBuilder $requestBuilder = null
|
||||
) {
|
||||
$this->apiKey = $apiKey;
|
||||
$this->restClient = new RestClient($apiKey, $apiEndpoint, $httpClient);
|
||||
|
||||
$this->httpClient = $httpClient;
|
||||
$this->requestBuilder = $requestBuilder ?: new RequestBuilder();
|
||||
$this->hydrator = $hydrator ?: new ModelHydrator();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param HttpClientConfigurator $configurator
|
||||
* @param Hydrator|null $hydrator
|
||||
* @param RequestBuilder|null $requestBuilder
|
||||
*
|
||||
* @return Mailgun
|
||||
*/
|
||||
public static function configure(
|
||||
HttpClientConfigurator $configurator,
|
||||
Hydrator $hydrator = null,
|
||||
RequestBuilder $requestBuilder = null
|
||||
) {
|
||||
$httpClient = $configurator->createConfiguredClient();
|
||||
$this->requestBuilder = $requestBuilder ?: new RequestBuilder();
|
||||
$this->hydrator = $hydrator ?: new ModelHydrator();
|
||||
|
||||
return new self($configurator->getApiKey(), $httpClient, 'api.mailgun.net', $hydrator, $requestBuilder);
|
||||
$this->httpClient = $configurator->createConfiguredClient();
|
||||
$this->apiKey = $configurator->getApiKey();
|
||||
$this->responseHistory = $configurator->getResponseHistory();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $apiKey
|
||||
* @param string $endpoint URL to mailgun servers
|
||||
*
|
||||
* @return Mailgun
|
||||
*/
|
||||
public static function create($apiKey, $endpoint = 'https://api.mailgun.net')
|
||||
public static function create(string $apiKey, string $endpoint = 'https://api.mailgun.net'): self
|
||||
{
|
||||
$httpClientConfigurator = (new HttpClientConfigurator())
|
||||
->setApiKey($apiKey)
|
||||
->setEndpoint($endpoint);
|
||||
|
||||
return self::configure($httpClientConfigurator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param string $workingDomain
|
||||
* @param array $postData
|
||||
* @param array $postFiles
|
||||
*
|
||||
* @throws Exceptions\MissingRequiredMIMEParameters
|
||||
*
|
||||
* @return \stdClass
|
||||
*
|
||||
* @deprecated Use Mailgun->messages()->send() instead. Will be removed in 3.0
|
||||
*/
|
||||
public function sendMessage($workingDomain, $postData, $postFiles = [])
|
||||
{
|
||||
if (is_array($postFiles)) {
|
||||
return $this->post("$workingDomain/messages", $postData, $postFiles);
|
||||
} elseif (is_string($postFiles)) {
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'MG_TMP_MIME');
|
||||
$fileHandle = fopen($tempFile, 'w');
|
||||
fwrite($fileHandle, $postFiles);
|
||||
|
||||
$result = $this->post("$workingDomain/messages.mime", $postData, ['message' => $tempFile]);
|
||||
fclose($fileHandle);
|
||||
unlink($tempFile);
|
||||
|
||||
return $result;
|
||||
} else {
|
||||
throw new Exceptions\MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function checks the signature in a POST request to see if it is
|
||||
* authentic.
|
||||
*
|
||||
* Pass an array of parameters. If you pass nothing, $_POST will be
|
||||
* used instead.
|
||||
*
|
||||
* If this function returns FALSE, you must not process the request.
|
||||
* You should reject the request with status code 403 Forbidden.
|
||||
*
|
||||
* @param array|null $postData
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @deprecated Use Mailgun->webhook() instead. Will be removed in 3.0
|
||||
*/
|
||||
public function verifyWebhookSignature($postData = null)
|
||||
{
|
||||
if (null === $postData) {
|
||||
$postData = $_POST;
|
||||
}
|
||||
if (!isset($postData['timestamp']) || !isset($postData['token']) || !isset($postData['signature'])) {
|
||||
return false;
|
||||
}
|
||||
$hmac = hash_hmac('sha256', "{$postData['timestamp']}{$postData['token']}", $this->apiKey);
|
||||
$sig = $postData['signature'];
|
||||
if (function_exists('hash_equals')) {
|
||||
// hash_equals is constant time, but will not be introduced until PHP 5.6
|
||||
return hash_equals($hmac, $sig);
|
||||
} else {
|
||||
return $hmac === $sig;
|
||||
}
|
||||
return new self($httpClientConfigurator);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -193,131 +77,6 @@ class Mailgun
|
||||
return $this->responseHistory->getLastResponse();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
* @param array $postData
|
||||
* @param array $files
|
||||
*
|
||||
* @return \stdClass
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function post($endpointUrl, $postData = [], $files = [])
|
||||
{
|
||||
return $this->restClient->post($endpointUrl, $postData, $files);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
* @param array $queryString
|
||||
*
|
||||
* @return \stdClass
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function get($endpointUrl, $queryString = [])
|
||||
{
|
||||
return $this->restClient->get($endpointUrl, $queryString);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $url
|
||||
*
|
||||
* @return \stdClass
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function getAttachment($url)
|
||||
{
|
||||
return $this->restClient->getAttachment($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
*
|
||||
* @return \stdClass
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function delete($endpointUrl)
|
||||
{
|
||||
return $this->restClient->delete($endpointUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $endpointUrl
|
||||
* @param array $putData
|
||||
*
|
||||
* @return \stdClass
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function put($endpointUrl, $putData)
|
||||
{
|
||||
return $this->restClient->put($endpointUrl, $putData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $apiVersion
|
||||
*
|
||||
* @return Mailgun
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function setApiVersion($apiVersion)
|
||||
{
|
||||
$this->restClient->setApiVersion($apiVersion);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $sslEnabled
|
||||
*
|
||||
* @return Mailgun
|
||||
*
|
||||
* @deprecated This will be removed in 3.0. Mailgun does not support non-secure connections to their API.
|
||||
*/
|
||||
public function setSslEnabled($sslEnabled)
|
||||
{
|
||||
$this->restClient->setSslEnabled($sslEnabled);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return MessageBuilder
|
||||
*
|
||||
* @deprecated Will be removed in 3.0.
|
||||
*/
|
||||
public function MessageBuilder()
|
||||
{
|
||||
return new MessageBuilder();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OptInHandler
|
||||
*
|
||||
* @deprecated Will be removed in 3.0
|
||||
*/
|
||||
public function OptInHandler()
|
||||
{
|
||||
return new OptInHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $workingDomain
|
||||
* @param bool $autoSend
|
||||
*
|
||||
* @return BatchMessage
|
||||
*
|
||||
* @deprecated Will be removed in 3.0. Use Mailgun::messages()::getBatchMessage().
|
||||
*/
|
||||
public function BatchMessage($workingDomain, $autoSend = true)
|
||||
{
|
||||
return new BatchMessage($this->restClient, $workingDomain, $autoSend);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Api\Stats
|
||||
*/
|
||||
|
@ -1,155 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Messages;
|
||||
|
||||
use Mailgun\Constants\Api;
|
||||
use Mailgun\Constants\ExceptionMessages;
|
||||
use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
|
||||
use Mailgun\Messages\Exceptions\TooManyParameters;
|
||||
|
||||
/**
|
||||
* This class is used for batch sending. See the official documentation (link below)
|
||||
* for usage instructions.
|
||||
*
|
||||
* @deprecated Will be removed in 3.0. Use Mailgun\Message\BatchMessage
|
||||
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Messages/README.md
|
||||
*/
|
||||
class BatchMessage extends MessageBuilder
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $batchRecipientAttributes;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $autoSend;
|
||||
|
||||
/**
|
||||
* @var \Mailgun\Connection\RestClient
|
||||
*/
|
||||
private $restClient;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $workingDomain;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $messageIds = [];
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $endpointUrl;
|
||||
|
||||
/**
|
||||
* @param \Mailgun\Connection\RestClient $restClient
|
||||
* @param string $workingDomain
|
||||
* @param bool $autoSend
|
||||
*/
|
||||
public function __construct($restClient, $workingDomain, $autoSend)
|
||||
{
|
||||
$this->batchRecipientAttributes = [];
|
||||
$this->autoSend = $autoSend;
|
||||
$this->restClient = $restClient;
|
||||
$this->workingDomain = $workingDomain;
|
||||
$this->endpointUrl = $workingDomain.'/messages';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $headerName
|
||||
* @param string $address
|
||||
* @param array $variables
|
||||
*
|
||||
* @throws MissingRequiredMIMEParameters
|
||||
* @throws TooManyParameters
|
||||
*/
|
||||
protected function addRecipient($headerName, $address, $variables)
|
||||
{
|
||||
if (array_key_exists($headerName, $this->counters['recipients'])) {
|
||||
if ($this->counters['recipients'][$headerName] == Api::RECIPIENT_COUNT_LIMIT) {
|
||||
if (false === $this->autoSend) {
|
||||
throw new TooManyParameters(ExceptionMessages::TOO_MANY_RECIPIENTS);
|
||||
}
|
||||
$this->sendMessage();
|
||||
}
|
||||
}
|
||||
|
||||
$compiledAddress = $this->parseAddress($address, $variables);
|
||||
|
||||
if (isset($this->message[$headerName])) {
|
||||
array_push($this->message[$headerName], $compiledAddress);
|
||||
} elseif ('h:reply-to' == $headerName) {
|
||||
$this->message[$headerName] = $compiledAddress;
|
||||
} else {
|
||||
$this->message[$headerName] = [$compiledAddress];
|
||||
}
|
||||
|
||||
if (array_key_exists($headerName, $this->counters['recipients'])) {
|
||||
$this->counters['recipients'][$headerName] += 1;
|
||||
if (is_array($variables) && !array_key_exists('id', $variables)) {
|
||||
$variables['id'] = $this->counters['recipients'][$headerName];
|
||||
}
|
||||
}
|
||||
$this->batchRecipientAttributes["$address"] = $variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $message
|
||||
* @param array $files
|
||||
*
|
||||
* @throws MissingRequiredMIMEParameters
|
||||
*/
|
||||
public function sendMessage($message = [], $files = [])
|
||||
{
|
||||
if (count($message) < 1) {
|
||||
$message = $this->message;
|
||||
$files = $this->files;
|
||||
}
|
||||
if (!array_key_exists('from', $message)) {
|
||||
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
|
||||
} elseif (!array_key_exists('to', $message)) {
|
||||
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
|
||||
} elseif (!array_key_exists('subject', $message)) {
|
||||
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
|
||||
} elseif ((!array_key_exists('text', $message) && !array_key_exists('html', $message))) {
|
||||
throw new MissingRequiredMIMEParameters(ExceptionMessages::EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
|
||||
} else {
|
||||
$message['recipient-variables'] = json_encode($this->batchRecipientAttributes);
|
||||
$response = $this->restClient->post($this->endpointUrl, $message, $files);
|
||||
$this->batchRecipientAttributes = [];
|
||||
$this->counters['recipients']['to'] = 0;
|
||||
$this->counters['recipients']['cc'] = 0;
|
||||
$this->counters['recipients']['bcc'] = 0;
|
||||
unset($this->message['to']);
|
||||
array_push($this->messageIds, $response->http_response_body->id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws MissingRequiredMIMEParameters
|
||||
*/
|
||||
public function finalize()
|
||||
{
|
||||
$this->sendMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getMessageIds()
|
||||
{
|
||||
return $this->messageIds;
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Messages\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
class InvalidParameter extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Messages\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
class InvalidParameterType extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Messages\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
class MissingRequiredMIMEParameters extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Messages\Exceptions;
|
||||
|
||||
use Mailgun\Exception;
|
||||
|
||||
class TooManyParameters extends \Exception implements Exception
|
||||
{
|
||||
}
|
@ -1,530 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Messages;
|
||||
|
||||
use Mailgun\Constants\Api;
|
||||
use Mailgun\Constants\ExceptionMessages;
|
||||
use Mailgun\Messages\Exceptions\InvalidParameter;
|
||||
use Mailgun\Messages\Exceptions\TooManyParameters;
|
||||
|
||||
/**
|
||||
* 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 (link below) for usage instructions.
|
||||
*
|
||||
* @deprecated Will be removed in 3.0. Use Mailgun\Message\MessageBuilder
|
||||
* @see https://github.com/mailgun/mailgun-php/blob/master/src/Mailgun/Messages/README.md
|
||||
*/
|
||||
class MessageBuilder
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $message = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $variables = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $files = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $counters = [
|
||||
'recipients' => [
|
||||
'to' => 0,
|
||||
'cc' => 0,
|
||||
'bcc' => 0,
|
||||
],
|
||||
'attributes' => [
|
||||
'attachment' => 0,
|
||||
'campaign_id' => 0,
|
||||
'custom_option' => 0,
|
||||
'tag' => 0,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function safeGet($params, $key, $default)
|
||||
{
|
||||
if (array_key_exists($key, $params)) {
|
||||
return $params[$key];
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
*
|
||||
* @return mixed|string
|
||||
*/
|
||||
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', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $address
|
||||
* @param array $variables
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function parseAddress($address, $variables)
|
||||
{
|
||||
if (!is_array($variables)) {
|
||||
return $address;
|
||||
}
|
||||
$fullName = $this->getFullName($variables);
|
||||
if (null != $fullName) {
|
||||
return sprintf('"%s" <%s>', $fullName, $address);
|
||||
}
|
||||
|
||||
return $address;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $headerName
|
||||
* @param string $address
|
||||
* @param array $variables
|
||||
*/
|
||||
protected function addRecipient($headerName, $address, $variables)
|
||||
{
|
||||
$compiledAddress = $this->parseAddress($address, $variables);
|
||||
|
||||
if ('h:reply-to' === $headerName) {
|
||||
$this->message[$headerName] = $compiledAddress;
|
||||
} elseif (isset($this->message[$headerName])) {
|
||||
array_push($this->message[$headerName], $compiledAddress);
|
||||
} else {
|
||||
$this->message[$headerName] = [$compiledAddress];
|
||||
}
|
||||
if (array_key_exists($headerName, $this->counters['recipients'])) {
|
||||
$this->counters['recipients'][$headerName] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $address
|
||||
* @param array|null $variables
|
||||
*
|
||||
* @throws TooManyParameters
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function addToRecipient($address, $variables = null)
|
||||
{
|
||||
if ($this->counters['recipients']['to'] > Api::RECIPIENT_COUNT_LIMIT) {
|
||||
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
|
||||
}
|
||||
|
||||
$variables = is_array($variables) ? $variables : [];
|
||||
|
||||
$this->addRecipient('to', $address, $variables);
|
||||
|
||||
return end($this->message['to']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $address
|
||||
* @param array|null $variables
|
||||
*
|
||||
* @throws TooManyParameters
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function addCcRecipient($address, $variables = null)
|
||||
{
|
||||
if ($this->counters['recipients']['cc'] > Api::RECIPIENT_COUNT_LIMIT) {
|
||||
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
|
||||
}
|
||||
|
||||
$variables = is_array($variables) ? $variables : [];
|
||||
|
||||
$this->addRecipient('cc', $address, $variables);
|
||||
|
||||
return end($this->message['cc']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $address
|
||||
* @param array|null $variables
|
||||
*
|
||||
* @throws TooManyParameters
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function addBccRecipient($address, $variables = null)
|
||||
{
|
||||
if ($this->counters['recipients']['bcc'] > Api::RECIPIENT_COUNT_LIMIT) {
|
||||
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_RECIPIENT);
|
||||
}
|
||||
|
||||
$variables = is_array($variables) ? $variables : [];
|
||||
|
||||
$this->addRecipient('bcc', $address, $variables);
|
||||
|
||||
return end($this->message['bcc']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $address
|
||||
* @param array|null $variables
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function setFromAddress($address, $variables = null)
|
||||
{
|
||||
$variables = is_array($variables) ? $variables : [];
|
||||
|
||||
$this->addRecipient('from', $address, $variables);
|
||||
|
||||
return $this->message['from'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $address
|
||||
* @param array|null $variables
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function setReplyToAddress($address, $variables = null)
|
||||
{
|
||||
$variables = is_array($variables) ? $variables : [];
|
||||
|
||||
$this->addRecipient('h:reply-to', $address, $variables);
|
||||
|
||||
return $this->message['h:reply-to'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $subject
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function setSubject($subject = '')
|
||||
{
|
||||
if (null == $subject || '' == $subject) {
|
||||
$subject = ' ';
|
||||
}
|
||||
$this->message['subject'] = $subject;
|
||||
|
||||
return $this->message['subject'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $headerName
|
||||
* @param mixed $headerData
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function addCustomHeader($headerName, $headerData)
|
||||
{
|
||||
if (!preg_match('/^h:/i', $headerName)) {
|
||||
$headerName = 'h:'.$headerName;
|
||||
}
|
||||
|
||||
if (array_key_exists($headerName, $this->message)) {
|
||||
if (is_array($this->message[$headerName])) {
|
||||
$this->message[$headerName][] = $headerData;
|
||||
} else {
|
||||
$this->message[$headerName] = [$this->message[$headerName], $headerData];
|
||||
}
|
||||
} else {
|
||||
$this->message[$headerName] = $headerData;
|
||||
}
|
||||
|
||||
return $this->message[$headerName];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $textBody
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function setTextBody($textBody)
|
||||
{
|
||||
if (null == $textBody || '' == $textBody) {
|
||||
$textBody = ' ';
|
||||
}
|
||||
$this->message['text'] = $textBody;
|
||||
|
||||
return $this->message['text'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $htmlBody
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function setHtmlBody($htmlBody)
|
||||
{
|
||||
if (null == $htmlBody || '' == $htmlBody) {
|
||||
$htmlBody = ' ';
|
||||
}
|
||||
$this->message['html'] = $htmlBody;
|
||||
|
||||
return $this->message['html'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $attachmentPath
|
||||
* @param string|null $attachmentName
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function addAttachment($attachmentPath, $attachmentName = null)
|
||||
{
|
||||
if (isset($this->files['attachment'])) {
|
||||
$attachment = [
|
||||
'filePath' => $attachmentPath,
|
||||
'remoteName' => $attachmentName,
|
||||
];
|
||||
array_push($this->files['attachment'], $attachment);
|
||||
} else {
|
||||
$this->files['attachment'] = [
|
||||
[
|
||||
'filePath' => $attachmentPath,
|
||||
'remoteName' => $attachmentName,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $inlineImagePath
|
||||
* @param string|null $inlineImageName
|
||||
*
|
||||
* @throws InvalidParameter
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function addInlineImage($inlineImagePath, $inlineImageName = null)
|
||||
{
|
||||
if (0 !== strpos($inlineImagePath, '@')) {
|
||||
throw new InvalidParameter(ExceptionMessages::INVALID_PARAMETER_INLINE);
|
||||
}
|
||||
|
||||
$this->files['inline'][] = [
|
||||
'filePath' => $inlineImagePath,
|
||||
'remoteName' => $inlineImageName,
|
||||
];
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $testMode
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function setTestMode($testMode)
|
||||
{
|
||||
if (filter_var($testMode, FILTER_VALIDATE_BOOLEAN)) {
|
||||
$testMode = 'yes';
|
||||
} else {
|
||||
$testMode = 'no';
|
||||
}
|
||||
$this->message['o:testmode'] = $testMode;
|
||||
|
||||
return $this->message['o:testmode'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|int $campaignId
|
||||
*
|
||||
* @throws TooManyParameters
|
||||
*
|
||||
* @return string|int
|
||||
*/
|
||||
public function addCampaignId($campaignId)
|
||||
{
|
||||
if ($this->counters['attributes']['campaign_id'] < Api::CAMPAIGN_ID_LIMIT) {
|
||||
if (isset($this->message['o:campaign'])) {
|
||||
array_push($this->message['o:campaign'], (string) $campaignId);
|
||||
} else {
|
||||
$this->message['o:campaign'] = [(string) $campaignId];
|
||||
}
|
||||
$this->counters['attributes']['campaign_id'] += 1;
|
||||
|
||||
return $this->message['o:campaign'];
|
||||
} else {
|
||||
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_CAMPAIGNS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $tag
|
||||
*
|
||||
* @throws TooManyParameters
|
||||
*/
|
||||
public function addTag($tag)
|
||||
{
|
||||
if ($this->counters['attributes']['tag'] < Api::TAG_LIMIT) {
|
||||
if (isset($this->message['o:tag'])) {
|
||||
array_push($this->message['o:tag'], $tag);
|
||||
} else {
|
||||
$this->message['o:tag'] = [$tag];
|
||||
}
|
||||
$this->counters['attributes']['tag'] += 1;
|
||||
|
||||
return $this->message['o:tag'];
|
||||
} else {
|
||||
throw new TooManyParameters(ExceptionMessages::TOO_MANY_PARAMETERS_TAGS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $enabled
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function setDkim($enabled)
|
||||
{
|
||||
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
|
||||
$enabled = 'yes';
|
||||
} else {
|
||||
$enabled = 'no';
|
||||
}
|
||||
$this->message['o:dkim'] = $enabled;
|
||||
|
||||
return $this->message['o:dkim'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $enabled
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function setOpenTracking($enabled)
|
||||
{
|
||||
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
|
||||
$enabled = 'yes';
|
||||
} else {
|
||||
$enabled = 'no';
|
||||
}
|
||||
$this->message['o:tracking-opens'] = $enabled;
|
||||
|
||||
return $this->message['o:tracking-opens'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $enabled
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function setClickTracking($enabled)
|
||||
{
|
||||
if (filter_var($enabled, FILTER_VALIDATE_BOOLEAN)) {
|
||||
$enabled = 'yes';
|
||||
} elseif ('html' == $enabled) {
|
||||
$enabled = 'html';
|
||||
} else {
|
||||
$enabled = 'no';
|
||||
}
|
||||
$this->message['o:tracking-clicks'] = $enabled;
|
||||
|
||||
return $this->message['o:tracking-clicks'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $timeDate
|
||||
* @param string|null $timeZone
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function setDeliveryTime($timeDate, $timeZone = null)
|
||||
{
|
||||
if (isset($timeZone)) {
|
||||
$timeZoneObj = new \DateTimeZone("$timeZone");
|
||||
} else {
|
||||
$timeZoneObj = new \DateTimeZone(Api::DEFAULT_TIME_ZONE);
|
||||
}
|
||||
|
||||
$dateTimeObj = new \DateTime($timeDate, $timeZoneObj);
|
||||
$formattedTimeDate = $dateTimeObj->format(\DateTime::RFC2822);
|
||||
$this->message['o:deliverytime'] = $formattedTimeDate;
|
||||
|
||||
return $this->message['o:deliverytime'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $customName
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function addCustomData($customName, $data)
|
||||
{
|
||||
$this->message['v:'.$customName] = json_encode($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $parameterName
|
||||
* @param mixed $data
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function addCustomParameter($parameterName, $data)
|
||||
{
|
||||
if (isset($this->message[$parameterName])) {
|
||||
array_push($this->message[$parameterName], $data);
|
||||
|
||||
return $this->message[$parameterName];
|
||||
} else {
|
||||
$this->message[$parameterName] = [$data];
|
||||
|
||||
return $this->message[$parameterName];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $message
|
||||
*/
|
||||
public function setMessage($message)
|
||||
{
|
||||
$this->message = $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getMessage()
|
||||
{
|
||||
return $this->message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getFiles()
|
||||
{
|
||||
return $this->files;
|
||||
}
|
||||
}
|
@ -1,136 +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(), $messageBldr->getFiles());
|
||||
```
|
||||
|
||||
Available Functions
|
||||
-----------------------------------------------------
|
||||
|
||||
`string addToRecipient(string $address, array $attributes)`
|
||||
|
||||
`string addCcRecipient(string $address, array $attributes)`
|
||||
|
||||
`string addBccRecipient(string $address, array $attributes)`
|
||||
|
||||
`string setFromAddress(string $address, array $attributes)`
|
||||
|
||||
`string setSubject(string $subject)`
|
||||
|
||||
`string setTextBody(string $textBody)`
|
||||
|
||||
`string setHtmlBody(string $htmlBody)`
|
||||
|
||||
`bool addAttachment(string $attachmentPath, $attachmentName = null)`
|
||||
|
||||
`bool addInlineImage(string $inlineImagePath)`
|
||||
|
||||
`string setTestMode(bool $testMode)`
|
||||
|
||||
`string addCampaignId(string $campaignId)`
|
||||
|
||||
`string setDkim(bool $enabled)`
|
||||
|
||||
`string setOpenTracking($enabled)`
|
||||
|
||||
`string setClickTracking($enabled)`
|
||||
|
||||
`string setDeliveryTime(string $timeDate, string $timeZone)`
|
||||
|
||||
`string addCustomData(string $optionName, string $data)`
|
||||
|
||||
`string addCustomParameter(string $parameterName, string $data)`
|
||||
|
||||
`array getMessage()`
|
||||
|
||||
`array 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@example.com", 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@example.com", array("first" => "John", "last" => "Doe"));
|
||||
$batchMsg->addToRecipient("sally.doe@example.com", array("first" => "Sally", "last" => "Doe"));
|
||||
$batchMsg->addToRecipient("mike.jones@example.com", array("first" => "Mike", "last" => "Jones"));
|
||||
...
|
||||
// After 1,000 recipients, 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)`
|
||||
|
||||
`sendMessage(array $message, array $files)`
|
||||
|
||||
`array finalize()`
|
||||
|
||||
More Documentation
|
||||
------------------
|
||||
See the official [Mailgun Docs](http://documentation.mailgun.com/api-sending.html)
|
||||
for more information.
|
@ -1,57 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Functional;
|
||||
|
||||
/**
|
||||
* Add attachment with file from memory.
|
||||
*
|
||||
* @author Wim Verstuyf <wim.verstuyf@codelicious.be>
|
||||
*/
|
||||
class FileFromMemoryTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testAddFileFromMemory()
|
||||
{
|
||||
$fileValidator = function ($files) {
|
||||
// Get only the attachments so the properties can be converted to a format we like
|
||||
$attachments = array_filter($files, function ($f) {
|
||||
return false !== strpos($f['name'], 'attachment');
|
||||
});
|
||||
|
||||
// Convert resources to strings
|
||||
$attachments = array_map(function ($f) {
|
||||
return [
|
||||
'name' => $f['name'],
|
||||
'contents' => fread($f['contents'], 50),
|
||||
'filename' => $f['filename'],
|
||||
];
|
||||
}, $attachments);
|
||||
|
||||
$this->assertContains(['name' => 'attachment', 'contents' => 'File content', 'filename' => 'file1.txt'], $attachments);
|
||||
$this->assertContains(['name' => 'attachment', 'contents' => 'File content 2', 'filename' => 'file2.txt'], $attachments);
|
||||
$this->assertContains(['name' => 'attachment', 'contents' => 'Contents of a text file', 'filename' => 'text_file.txt'], $attachments);
|
||||
};
|
||||
|
||||
$attachments = [
|
||||
['filename' => 'file1.txt', 'fileContent' => 'File content'],
|
||||
['filename' => 'file2.txt', 'fileContent' => 'File content 2'],
|
||||
['filePath' => './tests/TestAssets/text_file.txt', 'remoteName' => 'text_file.txt'],
|
||||
];
|
||||
|
||||
$mailgun = MockedMailgun::createMock($this, 'POST', 'domain/messages', [], $fileValidator);
|
||||
|
||||
$mailgun->sendMessage('domain', [
|
||||
'from' => 'bob@example.com',
|
||||
'to' => 'alice@example.com',
|
||||
'subject' => 'Foo',
|
||||
'text' => 'Bar', ], [
|
||||
'attachment' => $attachments,
|
||||
]);
|
||||
}
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Functional;
|
||||
|
||||
/**
|
||||
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
*/
|
||||
class InlineFileTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testSimpleExample()
|
||||
{
|
||||
$fileValidator = function ($files) {
|
||||
$fileNames = [
|
||||
['name' => 'inline', 'filename' => 'foo.png'],
|
||||
['name' => 'inline', 'filename' => 'bar.png'],
|
||||
];
|
||||
|
||||
// Make sure that both files exists
|
||||
foreach ($fileNames as $idx => $fileName) {
|
||||
foreach ($files as $file) {
|
||||
if ($file['name'] === $fileName['name'] && $file['filename'] === $fileName['filename']) {
|
||||
unset($fileNames[$idx]);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertEmpty($fileNames, 'Filenames could not be found');
|
||||
};
|
||||
|
||||
// Create the mocked mailgun client. We use $this->assertEquals on $method, $uri and $body parameters.
|
||||
$mailgun = MockedMailgun::createMock($this, 'POST', 'domain/messages', [], $fileValidator);
|
||||
|
||||
$builder = $mailgun->MessageBuilder();
|
||||
$builder->setFromAddress('bob@example.com');
|
||||
$builder->addToRecipient('alice@example.com');
|
||||
$builder->setSubject('Foo');
|
||||
$builder->setTextBody('Bar');
|
||||
|
||||
$builder->addInlineImage('@./tests/TestAssets/mailgun_icon1.png', 'foo.png');
|
||||
$builder->addInlineImage('@./tests/TestAssets/mailgun_icon2.png', 'bar.png');
|
||||
|
||||
$mailgun->post('domain/messages', $builder->getMessage(), $builder->getFiles());
|
||||
}
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Functional;
|
||||
|
||||
/**
|
||||
* @author James Kraus <jkraus@imagineteam.com>
|
||||
*/
|
||||
class MessageBuilderHeaderTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testSimpleExample()
|
||||
{
|
||||
$messageValidator = function ($headers) {
|
||||
$this->assertContains(['name' => 'h:My-Singular-Header', 'contents' => '123'], $headers);
|
||||
$this->assertContains(['name' => 'h:My-Plural-Header', 'contents' => '123'], $headers);
|
||||
$this->assertContains(['name' => 'h:My-Plural-Header', 'contents' => '456'], $headers);
|
||||
};
|
||||
|
||||
// Create the mocked mailgun client.
|
||||
$mailgun = MockedMailgun::createMock($this, 'POST', 'domain/messages', [], $messageValidator);
|
||||
|
||||
$builder = $mailgun->MessageBuilder();
|
||||
|
||||
$builder->addCustomHeader('My-Singular-Header', '123');
|
||||
$builder->addCustomHeader('My-Plural-Header', '123');
|
||||
$builder->addCustomHeader('My-Plural-Header', '456');
|
||||
|
||||
$builder->setFromAddress('from@example.com');
|
||||
$builder->addToRecipient('to@example.com');
|
||||
$builder->setSubject('Foo');
|
||||
$builder->setTextBody('Bar');
|
||||
|
||||
$mailgun->sendMessage('domain', $builder->getMessage());
|
||||
}
|
||||
}
|
@ -1,92 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Functional;
|
||||
|
||||
use Mailgun\Mailgun;
|
||||
|
||||
/**
|
||||
* A client to be used in tests.
|
||||
*
|
||||
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
*/
|
||||
final class MockedMailgun extends Mailgun
|
||||
{
|
||||
/**
|
||||
* @param MockedRestClient $restClient
|
||||
*
|
||||
* @internal Use MockedMailgun::create()
|
||||
*/
|
||||
public function __construct(MockedRestClient $restClient)
|
||||
{
|
||||
$this->apiKey = 'apikey';
|
||||
$this->restClient = $restClient;
|
||||
}
|
||||
|
||||
public function getMockedRestClient()
|
||||
{
|
||||
return $this->restClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a mocked mailgun client with a mocked RestClient.
|
||||
*
|
||||
* @param \PHPUnit_Framework_TestCase $testCase
|
||||
* @param \Closure|string $methodValidator
|
||||
* @param \Closure|string $uriValidator
|
||||
* @param \Closure|mixed $bodyValidator
|
||||
* @param \Closure|array $filesValidator
|
||||
* @param \Closure|array $headersValidator
|
||||
*/
|
||||
public static function createMock(
|
||||
\PHPUnit_Framework_TestCase $testCase,
|
||||
$methodValidator,
|
||||
$uriValidator,
|
||||
$bodyValidator = null,
|
||||
$filesValidator = [],
|
||||
$headersValidator = []
|
||||
) {
|
||||
if (!$methodValidator instanceof \Closure) {
|
||||
$methodValidator = self::createClosure($testCase, $methodValidator);
|
||||
}
|
||||
|
||||
if (!$uriValidator instanceof \Closure) {
|
||||
$uriValidator = self::createClosure($testCase, $uriValidator);
|
||||
}
|
||||
|
||||
if (!$bodyValidator instanceof \Closure) {
|
||||
$bodyValidator = self::createClosure($testCase, $bodyValidator);
|
||||
}
|
||||
|
||||
if (!$filesValidator instanceof \Closure) {
|
||||
$filesValidator = self::createClosure($testCase, $filesValidator);
|
||||
}
|
||||
|
||||
if (!$headersValidator instanceof \Closure) {
|
||||
$headersValidator = self::createClosure($testCase, $headersValidator);
|
||||
}
|
||||
|
||||
return new self(new MockedRestClient($methodValidator, $uriValidator, $bodyValidator, $filesValidator, $headersValidator));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a closure.
|
||||
*
|
||||
* @param \PHPUnit_Framework_TestCase $testCase
|
||||
* @param $expectedValue
|
||||
*
|
||||
* @return \Closure
|
||||
*/
|
||||
private static function createClosure(\PHPUnit_Framework_TestCase $testCase, $expectedValue)
|
||||
{
|
||||
return function ($value) use ($testCase, $expectedValue) {
|
||||
$testCase->assertEquals($expectedValue, $value);
|
||||
};
|
||||
}
|
||||
}
|
@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Functional;
|
||||
|
||||
use Mailgun\Connection\RestClient;
|
||||
|
||||
/**
|
||||
* A rest client that validate arguments to the send method.
|
||||
*
|
||||
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class MockedRestClient extends RestClient
|
||||
{
|
||||
/**
|
||||
* @var \Closure
|
||||
*/
|
||||
private $methodValidator;
|
||||
|
||||
/**
|
||||
* @var \Closure
|
||||
*/
|
||||
private $uriValidator;
|
||||
|
||||
/**
|
||||
* @var \Closure
|
||||
*/
|
||||
private $bodyValidator;
|
||||
|
||||
/**
|
||||
* @var \Closure
|
||||
*/
|
||||
private $filesValidator;
|
||||
|
||||
/**
|
||||
* @var \Closure
|
||||
*/
|
||||
private $headersValidator;
|
||||
|
||||
/**
|
||||
* @param \Closure $methodValidator
|
||||
* @param \Closure $uriValidator
|
||||
* @param \Closure $bodyValidator
|
||||
* @param \Closure $filesValidator
|
||||
* @param \Closure $headersValidator
|
||||
*
|
||||
* @internal Do not use this constructor. Use MockedMailgun::create()
|
||||
*/
|
||||
public function __construct(
|
||||
\Closure $methodValidator,
|
||||
\Closure $uriValidator,
|
||||
\Closure $bodyValidator,
|
||||
\Closure $filesValidator,
|
||||
\Closure $headersValidator
|
||||
) {
|
||||
$this->methodValidator = $methodValidator;
|
||||
$this->uriValidator = $uriValidator;
|
||||
$this->bodyValidator = $bodyValidator;
|
||||
$this->filesValidator = $filesValidator;
|
||||
$this->headersValidator = $headersValidator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override the send function and validate the parameters.
|
||||
*/
|
||||
protected function send($method, $uri, $body = null, $files = [], array $headers = [])
|
||||
{
|
||||
$f = $this->methodValidator;
|
||||
$f($method);
|
||||
|
||||
$f = $this->uriValidator;
|
||||
$f($uri);
|
||||
|
||||
$f = $this->bodyValidator;
|
||||
$f($body);
|
||||
|
||||
$f = $this->filesValidator;
|
||||
$f($files);
|
||||
|
||||
$f = $this->headersValidator;
|
||||
$f($headers);
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Functional;
|
||||
|
||||
/**
|
||||
* Simple test to show how to use the MockedMailgun client.
|
||||
*
|
||||
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
*/
|
||||
class SendMessageTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testSimpleExample()
|
||||
{
|
||||
// Create a Closure that validates the $files parameter to RestClient::send()
|
||||
$fileValidator = function ($files) {
|
||||
$this->assertContains(['name' => 'from', 'contents' => 'bob@example.com'], $files);
|
||||
$this->assertContains(['name' => 'to', 'contents' => 'alice@example.com'], $files);
|
||||
$this->assertContains(['name' => 'subject', 'contents' => 'Foo'], $files);
|
||||
$this->assertContains(['name' => 'text', 'contents' => 'Bar'], $files);
|
||||
};
|
||||
|
||||
// Create the mocked mailgun client. We use $this->assertEquals on $method, $uri and $body parameters.
|
||||
$mailgun = MockedMailgun::createMock($this, 'POST', 'domain/messages', [], $fileValidator);
|
||||
|
||||
$mailgun->sendMessage('domain', [
|
||||
'from' => 'bob@example.com',
|
||||
'to' => 'alice@example.com',
|
||||
'subject' => 'Foo',
|
||||
'text' => 'Bar', ]);
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Lists;
|
||||
|
||||
use Mailgun\Tests\Mock\Mailgun;
|
||||
|
||||
class OptInHandlerTest extends \Mailgun\Tests\MailgunTestCase
|
||||
{
|
||||
private $client;
|
||||
|
||||
private $optInHandler;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
$this->client = new Mailgun('My-Super-Awesome-API-Key');
|
||||
$this->optInHandler = $this->client->OptInHandler();
|
||||
}
|
||||
|
||||
public function testReturnOfGenerateHash()
|
||||
{
|
||||
$generatedHash = $this->optInHandler->generateHash(
|
||||
'mytestlist@example.com',
|
||||
'mysupersecretappid',
|
||||
'testrecipient@example.com'
|
||||
);
|
||||
$knownHash = 'eyJoIjoiMTllODc2YWNkMWRmNzk4NTc0ZTU0YzhjMzIzOTNiYTNjNzdhNGMxOCIsInAiOiJleUp5SWpvaWRHVnpkSEpsWTJsd2FXVnVkRUJsZUdGdGNHeGxMbU52YlNJc0ltd2lPaUp0ZVhSbGMzUnNhWE4wUUdWNFlXMXdiR1V1WTI5dEluMD0ifQ%3D%3D';
|
||||
$this->assertEquals($generatedHash, $knownHash);
|
||||
}
|
||||
|
||||
public function testGoodHash()
|
||||
{
|
||||
$validation = $this->optInHandler->validateHash(
|
||||
'mysupersecretappid',
|
||||
'eyJoIjoiMTllODc2YWNkMWRmNzk4NTc0ZTU0YzhjMzIzOTNiYTNjNzdhNGMxOCIsInAiOiJleUp5SWpvaWRHVnpkSEpsWTJsd2FXVnVkRUJsZUdGdGNHeGxMbU52YlNJc0ltd2lPaUp0ZVhSbGMzUnNhWE4wUUdWNFlXMXdiR1V1WTI5dEluMD0ifQ%3D%3D'
|
||||
);
|
||||
$this->assertArrayHasKey('recipientAddress', $validation);
|
||||
$this->assertArrayHasKey('mailingList', $validation);
|
||||
}
|
||||
|
||||
public function testBadHash()
|
||||
{
|
||||
$validation = $this->optInHandler->validateHash(
|
||||
'mybadsecretappid',
|
||||
'eyJoIjoiMTllODc2YWNkMWRmNzk4NTc0ZTU0YzhjMzIzOTNiYTNjNzdhNGMxOCIsInAiOiJleUp5SWpvaWRHVnpkSEpsWTJsd2FXVnVkRUJsZUdGdGNHeGxMbU52YlNJc0ltd2lPaUp0ZVhSbGMzUnNhWE4wUUdWNFlXMXdiR1V1WTI5dEluMD0ifQ%3D%3D'
|
||||
);
|
||||
$this->assertFalse($validation);
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests;
|
||||
|
||||
use Mailgun\Mailgun;
|
||||
|
||||
class MailgunTest extends \Mailgun\Tests\MailgunTestCase
|
||||
{
|
||||
public function testSendMessageMissingRequiredMIMEParametersExceptionGetsFlung()
|
||||
{
|
||||
$this->setExpectedException('\\Mailgun\\Messages\\Exceptions\\MissingRequiredMIMEParameters');
|
||||
|
||||
$client = new Mailgun();
|
||||
$client->sendMessage('test.mailgun.com', 'etss', 1);
|
||||
}
|
||||
|
||||
public function testVerifyWebhookGood()
|
||||
{
|
||||
$client = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
|
||||
$postData = [
|
||||
'timestamp' => '1403645220',
|
||||
'token' => '5egbgr1vjgqxtrnp65xfznchgdccwh5d6i09vijqi3whgowmn6',
|
||||
'signature' => '9cfc5c41582e51246e73c88d34db3af0a3a2692a76fbab81492842f000256d33',
|
||||
];
|
||||
assert($client->verifyWebhookSignature($postData));
|
||||
}
|
||||
|
||||
public function testVerifyWebhookBad()
|
||||
{
|
||||
$client = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
|
||||
$postData = [
|
||||
'timestamp' => '1403645220',
|
||||
'token' => 'owyldpe6nxhmrn78epljl6bj0orrki1u3d2v5e6cnlmmuox8jr',
|
||||
'signature' => '9cfc5c41582e51246e73c88d34db3af0a3a2692a76fbab81492842f000256d33',
|
||||
];
|
||||
assert(!$client->verifyWebhookSignature($postData));
|
||||
}
|
||||
|
||||
public function testVerifyWebhookEmptyRequest()
|
||||
{
|
||||
$client = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
|
||||
$postData = [];
|
||||
assert(!$client->verifyWebhookSignature($postData));
|
||||
}
|
||||
|
||||
public function testGetAttachmentOk()
|
||||
{
|
||||
$attachmentUrl = 'http://example.com';
|
||||
$client = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
|
||||
$response = $client->getAttachment($attachmentUrl);
|
||||
|
||||
$this->assertInstanceOf('stdClass', $response);
|
||||
$this->assertEquals($response->http_response_code, 200);
|
||||
}
|
||||
}
|
@ -1,194 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Messages;
|
||||
|
||||
use Mailgun\Tests\Mock\Mailgun;
|
||||
|
||||
class BatchMessageTest extends \Mailgun\Tests\MailgunTestCase
|
||||
{
|
||||
private $client;
|
||||
|
||||
private $sampleDomain = 'samples.mailgun.org';
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
$this->client = new Mailgun('My-Super-Awesome-API-Key');
|
||||
}
|
||||
|
||||
public function testBlankInstantiation()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$this->assertTrue(is_array($message->getMessage()));
|
||||
}
|
||||
|
||||
public function testAddRecipient()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addToRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['to' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('counters');
|
||||
$property->setAccessible(true);
|
||||
$array = $property->getValue($message);
|
||||
$this->assertEquals(1, $array['recipients']['to']);
|
||||
}
|
||||
|
||||
public function testAddRecipientWithoutFirstAndLastName()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addToRecipient('test@samples.mailgun.org', 'this-is-not-an-array');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['to' => ['test@samples.mailgun.org']], $messageObj);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('counters');
|
||||
$property->setAccessible(true);
|
||||
$array = $property->getValue($message);
|
||||
$this->assertEquals(1, $array['recipients']['to']);
|
||||
}
|
||||
|
||||
public function testRecipientVariablesOnTo()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addToRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['to' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('batchRecipientAttributes');
|
||||
$property->setAccessible(true);
|
||||
$propertyValue = $property->getValue($message);
|
||||
$this->assertEquals('Test', $propertyValue['test@samples.mailgun.org']['first']);
|
||||
$this->assertEquals('User', $propertyValue['test@samples.mailgun.org']['last']);
|
||||
}
|
||||
|
||||
public function testRecipientVariablesOnCc()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addCcRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['cc' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('batchRecipientAttributes');
|
||||
$property->setAccessible(true);
|
||||
$propertyValue = $property->getValue($message);
|
||||
$this->assertEquals('Test', $propertyValue['test@samples.mailgun.org']['first']);
|
||||
$this->assertEquals('User', $propertyValue['test@samples.mailgun.org']['last']);
|
||||
}
|
||||
|
||||
public function testRecipientVariablesOnBcc()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addBccRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['bcc' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('batchRecipientAttributes');
|
||||
$property->setAccessible(true);
|
||||
$propertyValue = $property->getValue($message);
|
||||
$this->assertEquals('Test', $propertyValue['test@samples.mailgun.org']['first']);
|
||||
$this->assertEquals('User', $propertyValue['test@samples.mailgun.org']['last']);
|
||||
}
|
||||
|
||||
public function testAddMultipleBatchRecipients()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
for ($i = 0; $i < 100; ++$i) {
|
||||
$message->addToRecipient("$i@samples.mailgun.org", ['first' => 'Test', 'last' => "User $i"]);
|
||||
}
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(100, count($messageObj['to']));
|
||||
}
|
||||
|
||||
public function testMaximumBatchSize()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->setFromAddress('samples@mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$message->setSubject('This is the subject of the message!');
|
||||
$message->setTextBody('This is the text body of the message!');
|
||||
for ($i = 0; $i < 1001; ++$i) {
|
||||
$message->addToRecipient("$i@samples.mailgun.org", ['first' => 'Test', 'last' => "User $i"]);
|
||||
}
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(1, count($messageObj['to']));
|
||||
}
|
||||
|
||||
public function testAttributeResetOnEndBatchMessage()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addToRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$message->setFromAddress('samples@mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$message->setSubject('This is the subject of the message!');
|
||||
$message->setTextBody('This is the text body of the message!');
|
||||
$message->finalize();
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertTrue(true, empty($messageObj));
|
||||
}
|
||||
|
||||
public function testDefaultIDInVariables()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addToRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('batchRecipientAttributes');
|
||||
$property->setAccessible(true);
|
||||
$propertyValue = $property->getValue($message);
|
||||
$this->assertEquals(1, $propertyValue['test-user@samples.mailgun.org']['id']);
|
||||
}
|
||||
|
||||
public function testgetMessageIds()
|
||||
{
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->addToRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$message->setFromAddress('samples@mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$message->setSubject('This is the subject of the message!');
|
||||
$message->setTextBody('This is the text body of the message!');
|
||||
$message->finalize();
|
||||
|
||||
$this->assertEquals(['1234'], $message->getMessageIds());
|
||||
}
|
||||
|
||||
public function testInvalidMissingRequiredMIMEParametersExceptionGetsFlungNoFrom()
|
||||
{
|
||||
$this->setExpectedException('\\Mailgun\\Messages\\Exceptions\\MissingRequiredMIMEParameters');
|
||||
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->sendMessage([1, 2, 3]);
|
||||
}
|
||||
|
||||
public function testInvalidMissingRequiredMIMEParametersExceptionGetsFlungNoTo()
|
||||
{
|
||||
$this->setExpectedException('\\Mailgun\\Messages\\Exceptions\\MissingRequiredMIMEParameters');
|
||||
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->sendMessage(['from' => 1, 2, 3]);
|
||||
}
|
||||
|
||||
public function testInvalidMissingRequiredMIMEParametersExceptionGetsFlungNoSubject()
|
||||
{
|
||||
$this->setExpectedException('\\Mailgun\\Messages\\Exceptions\\MissingRequiredMIMEParameters');
|
||||
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->sendMessage(['from' => 1, 'to' => 2, 3]);
|
||||
}
|
||||
|
||||
public function testInvalidMissingRequiredMIMEParametersExceptionGetsFlungNoTextOrHtml()
|
||||
{
|
||||
$this->setExpectedException('\\Mailgun\\Messages\\Exceptions\\MissingRequiredMIMEParameters');
|
||||
|
||||
$message = $this->client->BatchMessage($this->sampleDomain);
|
||||
$message->sendMessage(['from' => 1, 'to' => 2, 'subject' => 3]);
|
||||
}
|
||||
}
|
@ -1,116 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Messages;
|
||||
|
||||
use Http\Client\HttpClient;
|
||||
use Mailgun\Connection\RestClient;
|
||||
use Mailgun\Tests\Mock\Mailgun;
|
||||
|
||||
class mockRestClient extends RestClient
|
||||
{
|
||||
public function send($method, $uri, $body = null, $files = [], array $headers = [])
|
||||
{
|
||||
$result = new \stdClass();
|
||||
|
||||
$result->method = $method;
|
||||
$result->uri = $uri;
|
||||
$result->body = $body;
|
||||
$result->files = $files;
|
||||
$result->headers = $headers;
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
class mockMailgun extends Mailgun
|
||||
{
|
||||
public function __construct(
|
||||
$apiKey = null,
|
||||
HttpClient $httpClient = null,
|
||||
$apiEndpoint = 'api.mailgun.net'
|
||||
) {
|
||||
$this->apiKey = $apiKey;
|
||||
$this->restClient = new mockRestClient($apiKey, $apiEndpoint, $httpClient);
|
||||
}
|
||||
}
|
||||
|
||||
class ComplexMessageTest extends \Mailgun\Tests\MailgunTestCase
|
||||
{
|
||||
private $client;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
$this->client = new mockMailgun('My-Super-Awesome-API-Key');
|
||||
}
|
||||
|
||||
public function testSendComplexMessage()
|
||||
{
|
||||
$message = [
|
||||
'to' => 'test@test.mailgun.org',
|
||||
'from' => 'sender@test.mailgun.org',
|
||||
'subject' => 'This is my test subject',
|
||||
'text' => 'Testing!',
|
||||
];
|
||||
|
||||
$files = [
|
||||
'inline' => [
|
||||
[
|
||||
'remoteName' => 'mailgun_icon1.png',
|
||||
'filePath' => 'tests/TestAssets/mailgun_icon1.png',
|
||||
],
|
||||
[
|
||||
'remoteName' => 'mailgun_icon2.png',
|
||||
'filePath' => 'tests/TestAssets/mailgun_icon2.png',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$result = $this->client->sendMessage('test.mailgun.org', $message, $files);
|
||||
|
||||
$this->assertEquals('POST', $result->method);
|
||||
$this->assertEquals('test.mailgun.org/messages', $result->uri);
|
||||
$this->assertEquals([], $result->body);
|
||||
|
||||
// Start a counter, make sure all files are asserted
|
||||
$testCount = 0;
|
||||
|
||||
$expectedFilenames = ['mailgun_icon1.png', 'mailgun_icon2.png'];
|
||||
foreach ($result->files as $file) {
|
||||
if ('to' == $file['name']) {
|
||||
$this->assertEquals($file['contents'], 'test@test.mailgun.org');
|
||||
++$testCount;
|
||||
}
|
||||
if ('from' == $file['name']) {
|
||||
$this->assertEquals($file['contents'], 'sender@test.mailgun.org');
|
||||
++$testCount;
|
||||
}
|
||||
if ('subject' == $file['name']) {
|
||||
$this->assertEquals($file['contents'], 'This is my test subject');
|
||||
++$testCount;
|
||||
}
|
||||
if ('text' == $file['name']) {
|
||||
$this->assertEquals($file['contents'], 'Testing!');
|
||||
++$testCount;
|
||||
}
|
||||
if ('inline' == $file['name']) {
|
||||
$expectedFilename = array_shift($expectedFilenames);
|
||||
$this->assertNotNull($expectedFilename);
|
||||
$this->assertSame($expectedFilename, $file['filename']);
|
||||
++$testCount;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure all "files" are asserted
|
||||
$this->assertEquals(count($result->files), $testCount);
|
||||
|
||||
$this->assertEquals([], $result->body);
|
||||
$this->assertEquals([], $result->headers);
|
||||
}
|
||||
}
|
@ -1,382 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Messages;
|
||||
|
||||
use Mailgun\Tests\Mock\Mailgun;
|
||||
|
||||
class MessageBuilderTest extends \Mailgun\Tests\MailgunTestCase
|
||||
{
|
||||
private $client;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
$this->client = new Mailgun();
|
||||
}
|
||||
|
||||
public function testBlankInstantiation()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$this->assertTrue(is_array($message->getMessage()));
|
||||
}
|
||||
|
||||
public function testCountersSetToZero()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('counters');
|
||||
$property->setAccessible(true);
|
||||
$propertyValue = $property->getValue($message);
|
||||
$this->assertEquals(0, $propertyValue['recipients']['to']);
|
||||
$this->assertEquals(0, $propertyValue['recipients']['cc']);
|
||||
$this->assertEquals(0, $propertyValue['recipients']['bcc']);
|
||||
$this->assertEquals(0, $propertyValue['attributes']['attachment']);
|
||||
$this->assertEquals(0, $propertyValue['attributes']['campaign_id']);
|
||||
$this->assertEquals(0, $propertyValue['attributes']['custom_option']);
|
||||
$this->assertEquals(0, $propertyValue['attributes']['tag']);
|
||||
}
|
||||
|
||||
public function testAddToRecipient()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addToRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['to' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddCcRecipient()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCcRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['cc' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddBccRecipient()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addBccRecipient('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['bcc' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
}
|
||||
|
||||
public function testToRecipientCount()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addToRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('counters');
|
||||
$property->setAccessible(true);
|
||||
$array = $property->getValue($message);
|
||||
$this->assertEquals(1, $array['recipients']['to']);
|
||||
}
|
||||
|
||||
public function testCcRecipientCount()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCcRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('counters');
|
||||
$property->setAccessible(true);
|
||||
$array = $property->getValue($message);
|
||||
$this->assertEquals(1, $array['recipients']['cc']);
|
||||
}
|
||||
|
||||
public function testBccRecipientCount()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addBccRecipient('test-user@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
|
||||
$reflectionClass = new \ReflectionClass(get_class($message));
|
||||
$property = $reflectionClass->getProperty('counters');
|
||||
$property->setAccessible(true);
|
||||
$array = $property->getValue($message);
|
||||
$this->assertEquals(1, $array['recipients']['bcc']);
|
||||
}
|
||||
|
||||
public function testSetFromAddress()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setFromAddress('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['from' => ['"Test User" <test@samples.mailgun.org>']], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetReplyTo()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setReplyToAddress('overwritten@samples.mailgun.org');
|
||||
$message->setReplyToAddress('test@samples.mailgun.org', ['first' => 'Test', 'last' => 'User']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['h:reply-to' => '"Test User" <test@samples.mailgun.org>'], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetSubject()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setSubject('Test Subject');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['subject' => 'Test Subject'], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddCustomHeader()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCustomHeader('My-Header', '123');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['h:My-Header' => '123'], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddMultipleCustomHeader()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCustomHeader('My-Header', '123');
|
||||
$message->addCustomHeader('My-Header', '456');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['h:My-Header' => ['123', '456']], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetTextBody()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setTextBody('This is the text body!');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['text' => 'This is the text body!'], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetHtmlBody()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setHtmlBody('<html><body>This is an awesome email</body></html>');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['html' => '<html><body>This is an awesome email</body></html>'], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddAttachments()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addAttachment('@../TestAssets/mailgun_icon.png');
|
||||
$message->addAttachment('@../TestAssets/rackspace_logo.png');
|
||||
$messageObj = $message->getFiles();
|
||||
$this->assertEquals(
|
||||
[
|
||||
[
|
||||
'filePath' => '@../TestAssets/mailgun_icon.png',
|
||||
'remoteName' => null,
|
||||
],
|
||||
[
|
||||
'filePath' => '@../TestAssets/rackspace_logo.png',
|
||||
'remoteName' => null,
|
||||
],
|
||||
],
|
||||
$messageObj['attachment']
|
||||
);
|
||||
}
|
||||
|
||||
public function testAddInlineImages()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addInlineImage('@../TestAssets/mailgun_icon.png');
|
||||
$message->addInlineImage('@../TestAssets/rackspace_logo.png');
|
||||
$messageObj = $message->getFiles();
|
||||
$this->assertEquals(
|
||||
[
|
||||
[
|
||||
'filePath' => '@../TestAssets/mailgun_icon.png',
|
||||
'remoteName' => null,
|
||||
],
|
||||
[
|
||||
'filePath' => '@../TestAssets/rackspace_logo.png',
|
||||
'remoteName' => null,
|
||||
],
|
||||
],
|
||||
$messageObj['inline']
|
||||
);
|
||||
}
|
||||
|
||||
public function testAddAttachmentsPostName()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addAttachment('@../TestAssets/mailgun_icon.png', 'mg_icon.png');
|
||||
$message->addAttachment('@../TestAssets/rackspace_logo.png', 'rs_logo.png');
|
||||
$messageObj = $message->getFiles();
|
||||
$this->assertEquals(
|
||||
[
|
||||
[
|
||||
'filePath' => '@../TestAssets/mailgun_icon.png',
|
||||
'remoteName' => 'mg_icon.png',
|
||||
],
|
||||
[
|
||||
'filePath' => '@../TestAssets/rackspace_logo.png',
|
||||
'remoteName' => 'rs_logo.png',
|
||||
],
|
||||
],
|
||||
$messageObj['attachment']
|
||||
);
|
||||
}
|
||||
|
||||
public function testAddInlineImagePostName()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addInlineImage('@../TestAssets/mailgun_icon.png', 'mg_icon.png');
|
||||
$message->addInlineImage('@../TestAssets/rackspace_logo.png', 'rs_logo.png');
|
||||
$messageObj = $message->getFiles();
|
||||
$this->assertEquals(
|
||||
[
|
||||
[
|
||||
'filePath' => '@../TestAssets/mailgun_icon.png',
|
||||
'remoteName' => 'mg_icon.png',
|
||||
],
|
||||
[
|
||||
'filePath' => '@../TestAssets/rackspace_logo.png',
|
||||
'remoteName' => 'rs_logo.png',
|
||||
],
|
||||
],
|
||||
$messageObj['inline']
|
||||
);
|
||||
}
|
||||
|
||||
public function testSetTestMode()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setTestMode(true);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:testmode' => 'yes'], $messageObj);
|
||||
$message->setTestMode(false);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:testmode' => 'no'], $messageObj);
|
||||
$message->setTestMode('yes');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:testmode' => 'yes'], $messageObj);
|
||||
$message->setTestMode('no');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:testmode' => 'no'], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddCampaignId()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCampaignId('ABC123');
|
||||
$message->addCampaignId('XYZ987');
|
||||
$message->addCampaignId('TUV456');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:campaign' => ['ABC123', 'XYZ987', 'TUV456']], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddCampaignIdInteger()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCampaignId(1111);
|
||||
$message->addCampaignId(2222);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertSame(['o:campaign' => ['1111', '2222']], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetDkim()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setDkim(true);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:dkim' => 'yes'], $messageObj);
|
||||
$message->setDkim(false);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:dkim' => 'no'], $messageObj);
|
||||
$message->setDkim('yes');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:dkim' => 'yes'], $messageObj);
|
||||
$message->setDkim('no');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:dkim' => 'no'], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetClickTracking()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setClickTracking(true);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-clicks' => 'yes'], $messageObj);
|
||||
$message->setClickTracking(false);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-clicks' => 'no'], $messageObj);
|
||||
$message->setClickTracking('yes');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-clicks' => 'yes'], $messageObj);
|
||||
$message->setClickTracking('no');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-clicks' => 'no'], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetOpenTracking()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setOpenTracking(true);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-opens' => 'yes'], $messageObj);
|
||||
$message->setOpenTracking(false);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-opens' => 'no'], $messageObj);
|
||||
$message->setOpenTracking('yes');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-opens' => 'yes'], $messageObj);
|
||||
$message->setOpenTracking('no');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:tracking-opens' => 'no'], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetDeliveryTime()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->setDeliveryTime('January 15, 2014 8:00AM', 'CST');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 08:00:00 -0600'], $messageObj);
|
||||
$message->setDeliveryTime('January 15, 2014 8:00AM', 'UTC');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 08:00:00 +0000'], $messageObj);
|
||||
$message->setDeliveryTime('January 15, 2014 8:00AM');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 08:00:00 +0000'], $messageObj);
|
||||
$message->setDeliveryTime('1/15/2014 13:50:01', 'CDT');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['o:deliverytime' => 'Wed, 15 Jan 2014 13:50:01 -0600'], $messageObj);
|
||||
// https://github.com/mailgun/mailgun-php/pull/42
|
||||
// https://github.com/mailgun/mailgun-php/issues/43
|
||||
//$message->setDeliveryTime("first saturday of July 2013 8:00AM", "CDT");
|
||||
//$messageObj = $message->getMessage();
|
||||
//$this->assertEquals(array("o:deliverytime" => "Sat, 06 Jul 2013 08:00:00 -0500"), $messageObj);
|
||||
}
|
||||
|
||||
public function testAddCustomData()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCustomData('My-Super-Awesome-Data', ['What' => 'Mailgun Rocks!']);
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['v:My-Super-Awesome-Data' => '{"What":"Mailgun Rocks!"}'], $messageObj);
|
||||
}
|
||||
|
||||
public function testAddCustomParameter()
|
||||
{
|
||||
$message = $this->client->MessageBuilder();
|
||||
$message->addCustomParameter('my-option', 'yes');
|
||||
$message->addCustomParameter('o:my-other-option', 'no');
|
||||
$messageObj = $message->getMessage();
|
||||
$this->assertEquals(['my-option' => ['yes'], 'o:my-other-option' => ['no']], $messageObj);
|
||||
}
|
||||
|
||||
public function testSetMessage()
|
||||
{
|
||||
$message = [1, 2, 3, 4, 5];
|
||||
$messageBuilder = $this->client->MessageBuilder();
|
||||
$messageBuilder->setMessage($message);
|
||||
|
||||
$this->assertEquals($message, $messageBuilder->getMessage());
|
||||
}
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Messages;
|
||||
|
||||
use Mailgun\Tests\Mock\Mailgun;
|
||||
|
||||
class StandardMessageTest extends \Mailgun\Tests\MailgunTestCase
|
||||
{
|
||||
private $client;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
$this->client = new Mailgun('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 = ['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 = ['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);
|
||||
}
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Mock\Connection;
|
||||
|
||||
use Mailgun\Connection\Exceptions\GenericHTTPError;
|
||||
use Mailgun\Connection\Exceptions\InvalidCredentials;
|
||||
use Mailgun\Connection\Exceptions\MissingEndpoint;
|
||||
use Mailgun\Connection\RestClient;
|
||||
use Mailgun\Messages\Exceptions\MissingRequiredMIMEParameters;
|
||||
|
||||
class TestBroker extends RestClient
|
||||
{
|
||||
private $apiKey;
|
||||
|
||||
protected $apiEndpoint;
|
||||
|
||||
public function __construct($apiKey = null, $apiHost = 'api.mailgun.net', $apiVersion = 'v3')
|
||||
{
|
||||
$this->apiKey = $apiKey;
|
||||
$this->apiEndpoint = $apiHost;
|
||||
}
|
||||
|
||||
public function post($endpointUrl, array $postData = [], $files = [])
|
||||
{
|
||||
return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
|
||||
}
|
||||
|
||||
public function get($endpointUrl, $queryString = [])
|
||||
{
|
||||
return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
|
||||
}
|
||||
|
||||
public function delete($endpointUrl)
|
||||
{
|
||||
return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
|
||||
}
|
||||
|
||||
public function put($endpointUrl, $queryString)
|
||||
{
|
||||
return $this->testResponseHandler($endpointUrl, $httpResponseCode = 200);
|
||||
}
|
||||
|
||||
public function testResponseHandler($endpointUrl, $httpResponseCode = 200)
|
||||
{
|
||||
if (200 === $httpResponseCode) {
|
||||
$result = new \stdClass();
|
||||
$result->http_response_body = new \stdClass();
|
||||
$jsonResponseData = json_decode('{"message": "Some JSON Response Data", "id": "1234"}');
|
||||
foreach ($jsonResponseData as $key => $value) {
|
||||
$result->http_response_body->$key = $value;
|
||||
}
|
||||
} elseif (400 == $httpResponseCode) {
|
||||
throw new MissingRequiredMIMEParameters(EXCEPTION_MISSING_REQUIRED_MIME_PARAMETERS);
|
||||
} elseif (401 == $httpResponseCode) {
|
||||
throw new InvalidCredentials(EXCEPTION_INVALID_CREDENTIALS);
|
||||
} elseif (401 == $httpResponseCode) {
|
||||
throw new GenericHTTPError(EXCEPTION_INVALID_CREDENTIALS);
|
||||
} elseif (404 == $httpResponseCode) {
|
||||
throw new MissingEndpoint(EXCEPTION_MISSING_ENDPOINT);
|
||||
} else {
|
||||
throw new GenericHTTPError(EXCEPTION_GENERIC_HTTP_ERROR);
|
||||
return false;
|
||||
}
|
||||
$result->http_response_code = $httpResponseCode;
|
||||
$result->http_endpoint_url = $endpointUrl;
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright (C) 2013 Mailgun
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Mailgun\Tests\Mock;
|
||||
|
||||
use Mailgun\Mailgun as Base;
|
||||
use Mailgun\Tests\Mock\Connection\TestBroker;
|
||||
|
||||
class Mailgun extends Base
|
||||
{
|
||||
protected $debug;
|
||||
|
||||
protected $restClient;
|
||||
|
||||
public function __construct($apiKey = null, $apiEndpoint = 'api.mailgun.net', $apiVersion = 'v3')
|
||||
{
|
||||
$this->restClient = new TestBroker($apiKey, $apiEndpoint, $apiVersion);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user