Skip to content

Commit

Permalink
Added bulk email API (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
doobas committed Oct 13, 2021
1 parent 2e7f558 commit b5d283c
Show file tree
Hide file tree
Showing 8 changed files with 1,002 additions and 67 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add template endpoints
- Add the recipient/suppression lists endpoints
- Add domain verification endpoint
- Bulk email endpoints

### Changed

Expand Down
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ MailerSend PHP SDK
* [Advanced personalization](#personalization)
* [Simple personalization](#variables)
* [Send an email with attachment](#attachments)
* [Bulk emails API](#bulk-email-api)
* [Send bulk email](#send-bulk-email)
* [Get bulk email status](#get-bulk-email-status)
* [Activity API](#activity)
* [Get a list of activities](#get-a-list-of-activities)
* [Analytics API](#analytics)
Expand Down Expand Up @@ -322,6 +325,55 @@ $emailParams = (new EmailParams())
$mailersend->email->send($emailParams);
```

<a name="bulk-email-api"></a>
## Bulk email API

<a name="send-bulk-email"></a>
###Send bulk email

```php
use MailerSend\MailerSend;
use MailerSend\Helpers\Builder\Recipient;
use MailerSend\Helpers\Builder\EmailParams;

$mailersend = new MailerSend(['api_key' => 'key']);

$recipients = [
new Recipient('your@client.com', 'Your Client'),
];

$bulkEmailParams = [];

$bulkEmailParams[] = (new EmailParams())
->setFrom('your@domain.com')
->setFromName('Your Name')
->setRecipients($recipients)
->setSubject('Subject')
->setHtml('This is the HTML content')
->setText('This is the text content');

$bulkEmailParams[] = (new EmailParams())
->setFrom('your@domain.com')
->setFromName('Your Name')
->setRecipients($recipients)
->setSubject('Subject')
->setHtml('This is the HTML content')
->setText('This is the text content');

$mailersend->bulkEmail->send($bulkEmailParams);
```

<a name="get-bulk-email-status"></a>
###Get bulk email status

```php
use MailerSend\MailerSend;

$mailersend = new MailerSend(['api_key' => 'key']);

$mailersend->bulkEmail->getStatus('bulk_email_id');
```

<a name="activity"></a>

## Activity
Expand Down
23 changes: 23 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
bootstrap = "vendor/autoload.php"
backupGlobals = "false"
backupStaticAttributes = "false"
colors = "true"
convertErrorsToExceptions = "true"
convertNoticesToExceptions = "true"
convertWarningsToExceptions = "true"
processIsolation = "false"
stopOnFailure = "false">

<testsuites>
<testsuite name="MailerSend PHP SDK">
<directory>tests</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
</php>

</phpunit>
88 changes: 88 additions & 0 deletions src/Endpoints/BulkEmail.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace MailerSend\Endpoints;

use Assert\Assertion;
use MailerSend\Exceptions\MailerSendAssertException;
use MailerSend\Helpers\Builder\Attachment;
use MailerSend\Helpers\Builder\EmailParams;
use MailerSend\Helpers\Builder\Personalization;
use MailerSend\Helpers\Builder\Recipient;
use MailerSend\Helpers\Builder\Variable;
use MailerSend\Helpers\GeneralHelpers;
use Tightenco\Collect\Support\Collection;

class BulkEmail extends AbstractEndpoint
{
protected string $endpoint = 'bulk-email';

/**
* @throws \JsonException
* @throws \MailerSend\Exceptions\MailerSendAssertException
* @throws \Psr\Http\Client\ClientExceptionInterface
*/
public function send(array $bulkParams): array
{
GeneralHelpers::assert(fn () => Assertion::minCount($bulkParams, 1, 'Bulk params should contain at least 1 email'));

$requestData = [];

foreach ($bulkParams as $params) {
GeneralHelpers::validateEmailParams($params);

$recipients_mapped = GeneralHelpers::mapToArray($params->getRecipients(), Recipient::class);
$cc_mapped = GeneralHelpers::mapToArray($params->getCc(), Recipient::class);
$bcc_mapped = GeneralHelpers::mapToArray($params->getBcc(), Recipient::class);
$attachments_mapped = GeneralHelpers::mapToArray($params->getAttachments(), Attachment::class);
$variables_mapped = GeneralHelpers::mapToArray($params->getVariables(), Variable::class);
$personalization_mapped = GeneralHelpers::mapToArray($params->getPersonalization(), Personalization::class);

$requestData[] = array_filter(
[
'from' => [
'email' => $params->getFrom(),
'name' => $params->getFromName(),
],
'reply_to' => [
'email' => $params->getReplyTo(),
'name' => $params->getReplyToName(),
],
'to' => $recipients_mapped,
'cc' => $cc_mapped,
'bcc' => $bcc_mapped,
'subject' => $params->getSubject(),
'template_id' => $params->getTemplateId(),
'text' => $params->getText(),
'html' => $params->getHtml(),
'tags' => $params->getTags(),
'attachments' => $attachments_mapped,
'variables' => $variables_mapped,
'personalization' => $personalization_mapped
],
fn ($v) => is_array($v) ? array_filter($v, fn ($v) => $v !== null) : $v !== null
);
}

return $this->httpLayer->post(
$this->buildUri($this->endpoint),
$requestData
);
}

/**
* @param string $bulkEmailId
* @return array
* @throws \JsonException
* @throws \Psr\Http\Client\ClientExceptionInterface
*/
public function getStatus(string $bulkEmailId): array
{
GeneralHelpers::assert(
fn () => Assertion::minLength($bulkEmailId, 1, 'Bulk email id is required.')
);

return $this->httpLayer->get(
$this->buildUri("$this->endpoint/$bulkEmailId")
);
}
}
76 changes: 9 additions & 67 deletions src/Endpoints/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Assert\Assertion;
use MailerSend\Helpers\Builder\Attachment;
use MailerSend\Helpers\Builder\EmailParams;
use MailerSend\Helpers\Builder\Personalization;
use MailerSend\Helpers\Builder\Recipient;
use MailerSend\Helpers\Builder\Variable;
use MailerSend\Helpers\GeneralHelpers;
Expand All @@ -21,73 +22,14 @@ class Email extends AbstractEndpoint
*/
public function send(EmailParams $params): array
{
GeneralHelpers::assert(fn () => Assertion::notEmpty(array_filter([
$params->getTemplateId(), $params->getText()
], fn ($v) => $v !== null), 'One of template_id or text must be supplied'));

if (!$params->getTemplateId()) {
GeneralHelpers::assert(
fn () => Assertion::email($params->getFrom()) &&
Assertion::minLength($params->getFromName(), 1) &&
Assertion::minLength($params->getSubject(), 1) &&
Assertion::minCount($params->getRecipients(), 1)
);
} else {
GeneralHelpers::assert(fn () => Assertion::minCount($params->getRecipients(), 1));
}

if (count($params->getCc()) > 0) {
GeneralHelpers::assert(fn () => Assertion::maxCount($params->getCc(), 10));
foreach ($params->getCc() as $key => $cc) {
$cc = ! is_array($cc) ? $cc->toArray() : $cc;
GeneralHelpers::assert(
fn () => Assertion::keyExists($cc, 'email', "The element with index $key in CC array does not contain the email parameter.")
);
if (isset($cc['name'])) {
GeneralHelpers::assert(fn () => Assertion::eq(1, count(explode(';', $cc['name']))));
GeneralHelpers::assert(fn () => Assertion::eq(1, count(explode(',', $cc['name']))));
}
}
}

if (count($params->getBcc()) > 0) {
GeneralHelpers::assert(fn () => Assertion::maxCount($params->getBcc(), 10));
foreach ($params->getBcc() as $key => $bcc) {
$bcc = ! is_array($bcc) ? $bcc->toArray() : $bcc;
GeneralHelpers::assert(
fn () => Assertion::keyExists($bcc, 'email', "The element with index $key in BCC array does not contain the email parameter.")
);
if (isset($bcc['name'])) {
GeneralHelpers::assert(fn () => Assertion::eq(1, count(explode(';', $bcc['name']))));
GeneralHelpers::assert(fn () => Assertion::eq(1, count(explode(',', $bcc['name']))));
}
}
}

$recipients_mapped = (new Collection($params->getRecipients()))->map(fn ($v) => is_object($v) && is_a(
$v,
Recipient::class
) ? $v->toArray() : $v)->toArray();
$cc_mapped = (new Collection($params->getCc()))->map(fn ($v) => is_object($v) && is_a(
$v,
Recipient::class
) ? $v->toArray() : $v)->toArray();
$bcc_mapped = (new Collection($params->getBcc()))->map(fn ($v) => is_object($v) && is_a(
$v,
Recipient::class
) ? $v->toArray() : $v)->toArray();
$attachments_mapped = (new Collection($params->getAttachments()))->map(fn ($v) => is_object($v) && is_a(
$v,
Attachment::class
) ? $v->toArray() : $v)->toArray();
$variables_mapped = (new Collection($params->getVariables()))->map(fn ($v) => is_object($v) && is_a(
$v,
Variable::class
) ? $v->toArray() : $v)->toArray();
$personalization_mapped = (new Collection($params->getPersonalization()))->map(fn ($v) => is_object($v) && is_a(
$v,
\MailerSend\Helpers\Builder\Personalization::class
) ? $v->toArray() : $v)->toArray();
GeneralHelpers::validateEmailParams($params);

$recipients_mapped = GeneralHelpers::mapToArray($params->getRecipients(), Recipient::class);
$cc_mapped = GeneralHelpers::mapToArray($params->getCc(), Recipient::class);
$bcc_mapped = GeneralHelpers::mapToArray($params->getBcc(), Recipient::class);
$attachments_mapped = GeneralHelpers::mapToArray($params->getAttachments(), Attachment::class);
$variables_mapped = GeneralHelpers::mapToArray($params->getVariables(), Variable::class);
$personalization_mapped = GeneralHelpers::mapToArray($params->getPersonalization(), Personalization::class);

return $this->httpLayer->post(
$this->buildUri($this->endpoint),
Expand Down
61 changes: 61 additions & 0 deletions src/Helpers/GeneralHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

namespace MailerSend\Helpers;

use Assert\Assertion;
use Assert\AssertionFailedException;
use MailerSend\Exceptions\MailerSendAssertException;
use MailerSend\Helpers\Builder\EmailParams;
use Tightenco\Collect\Support\Collection;

class GeneralHelpers
{
Expand All @@ -19,4 +22,62 @@ public static function assert(callable $assertions): void
throw new MailerSendAssertException($e->getMessage());
}
}

/**
* @param EmailParams $params
* @throws MailerSendAssertException
*/
public static function validateEmailParams(EmailParams $params): void
{
self::assert(fn () => Assertion::notEmpty(array_filter([
$params->getTemplateId(), $params->getText()
], fn ($v) => $v !== null), 'One of template_id or text must be supplied'));

if (!$params->getTemplateId()) {
self::assert(
fn () => Assertion::email($params->getFrom()) &&
Assertion::minLength($params->getFromName(), 1) &&
Assertion::minLength($params->getSubject(), 1) &&
Assertion::minCount($params->getRecipients(), 1)
);
} else {
self::assert(fn () => Assertion::minCount($params->getRecipients(), 1));
}

if (count($params->getCc()) > 0) {
self::assert(fn () => Assertion::maxCount($params->getCc(), 10));
foreach ($params->getCc() as $key => $cc) {
$cc = ! is_array($cc) ? $cc->toArray() : $cc;
self::assert(
fn () => Assertion::keyExists($cc, 'email', "The element with index $key in CC array does not contain the email parameter.")
);
if (isset($cc['name'])) {
self::assert(fn () => Assertion::eq(1, count(explode(';', $cc['name']))));
self::assert(fn () => Assertion::eq(1, count(explode(',', $cc['name']))));
}
}
}

if (count($params->getBcc()) > 0) {
self::assert(fn () => Assertion::maxCount($params->getBcc(), 10));
foreach ($params->getBcc() as $key => $bcc) {
$bcc = ! is_array($bcc) ? $bcc->toArray() : $bcc;
self::assert(
fn () => Assertion::keyExists($bcc, 'email', "The element with index $key in BCC array does not contain the email parameter.")
);
if (isset($bcc['name'])) {
self::assert(fn () => Assertion::eq(1, count(explode(';', $bcc['name']))));
self::assert(fn () => Assertion::eq(1, count(explode(',', $bcc['name']))));
}
}
}
}

public static function mapToArray(array $data, string $object): array
{
return (new Collection($data))->map(fn ($v) => is_object($v) && is_a(
$v,
$object
) ? $v->toArray() : $v)->toArray();
}
}
3 changes: 3 additions & 0 deletions src/MailerSend.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use MailerSend\Endpoints\Activity;
use MailerSend\Endpoints\Analytics;
use MailerSend\Endpoints\Blocklist;
use MailerSend\Endpoints\BulkEmail;
use MailerSend\Endpoints\Domain;
use MailerSend\Endpoints\Email;
use MailerSend\Endpoints\HardBounce;
Expand Down Expand Up @@ -39,6 +40,7 @@ class MailerSend
protected ?HttpLayer $httpLayer;

public Email $email;
public BulkEmail $bulkEmail;
public Message $messages;
public Webhook $webhooks;
public Token $token;
Expand Down Expand Up @@ -67,6 +69,7 @@ public function __construct(array $options = [], ?HttpLayer $httpLayer = null)
protected function setEndpoints(): void
{
$this->email = new Email($this->httpLayer, $this->options);
$this->bulkEmail = new BulkEmail($this->httpLayer, $this->options);
$this->messages = new Message($this->httpLayer, $this->options);
$this->webhooks = new Webhook($this->httpLayer, $this->options);
$this->token = new Token($this->httpLayer, $this->options);
Expand Down
Loading

0 comments on commit b5d283c

Please sign in to comment.