Skip to content

Commit

Permalink
Merge pull request #23 from railsware/feature/buld-api
Browse files Browse the repository at this point in the history
Add Bulk Sending
  • Loading branch information
gaalferov authored Apr 22, 2024
2 parents 7d0d6d5 + 3c3d418 commit b00a943
Show file tree
Hide file tree
Showing 18 changed files with 732 additions and 373 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## [1.8.0] - 2024-04-19

- Support new functionality [Bulk Stream](https://help.mailtrap.io/article/113-sending-streams)

## [1.7.4] - 2024-03-20

- Add PHP 8.3 support (GitHub Actions)
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ try {
You can find more examples [here](examples).
* [General examples](examples/general)
* [Sending examples](examples/sending)
* [Bulk Sending examples](examples/bulkSending)
* [Sandbox examples](examples/sandbox)


Expand Down
113 changes: 113 additions & 0 deletions examples/bulkSending/emails.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

use Mailtrap\Config;
use Mailtrap\EmailHeader\CategoryHeader;
use Mailtrap\EmailHeader\CustomVariableHeader;
use Mailtrap\EmailHeader\Template\TemplateUuidHeader;
use Mailtrap\EmailHeader\Template\TemplateVariableHeader;
use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Header\UnstructuredHeader;

require __DIR__ . '/../vendor/autoload.php';

/**********************************************************************************************************************
******************************************* EMAIL BULK SENDING *******************************************************
**********************************************************************************************************************
*/

/**
* Email Bulk Sending API
*
* POST https://bulk.api.mailtrap.io/api/send
*/
try {
// your API token from here https://mailtrap.io/api-tokens
$apiKey = getenv('MAILTRAP_API_KEY');
$mailtrap = new MailtrapClient(new Config($apiKey));

$email = (new Email())
->from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // <--- you should use your domain here that you installed in the mailtrap.io admin area (otherwise you will get 401)
->replyTo(new Address('reply@YOUR-DOMAIN-HERE.com'))
->to(new Address('email@example.com', 'Jon'))
->priority(Email::PRIORITY_HIGH)
->cc('mailtrapqa@example.com')
->addCc('staging@example.com')
->bcc('mailtrapdev@example.com')
->subject('Best practices of building HTML emails')
->text('Hey! Learn the best practices of building HTML emails and play with ready-to-go templates. Mailtrap’s Guide on How to Build HTML Email is live on our blog')
->html(
'<html>
<body>
<p><br>Hey</br>
Learn the best practices of building HTML emails and play with ready-to-go templates.</p>
<p><a href="https://mailtrap.io/blog/build-html-email/">Mailtrap’s Guide on How to Build HTML Email</a> is live on our blog</p>
<img src="cid:logo">
</body>
</html>'
)
->embed(fopen('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg', 'r'), 'logo', 'image/svg+xml')
->attachFromPath('README.md')
;

// Headers
$email->getHeaders()
->addTextHeader('X-Message-Source', '1alf.com')
->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client'))
;

// Custom Variables
$email->getHeaders()
->add(new CustomVariableHeader('user_id', '45982'))
->add(new CustomVariableHeader('batch_id', 'PSJ-12'))
;

// Category (should be only one)
$email->getHeaders()
->add(new CategoryHeader('Integration Test'))
;

$response = $mailtrap->bulkSending()->emails()->send($email);

var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}


/**
* Email Bulk Sending WITH TEMPLATE
*
* WARNING! If a template is provided, then subject, text, html, category and other params are forbidden.
*
* UUID of email template. Subject, text and html will be generated from template using optional template_variables.
* Optional template variables that will be used to generate actual subject, text and html from email template
*/
try {
// your API token from here https://mailtrap.io/api-tokens
$apiKey = getenv('MAILTRAP_API_KEY');
$mailtrap = new MailtrapClient(new Config($apiKey));

$email = (new Email())
->from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // <--- you should use your domain here that you installed in the mailtrap.io admin area (otherwise you will get 401)
->replyTo(new Address('reply@YOUR-DOMAIN-HERE.com'))
->to(new Address('example@gmail.com', 'Jon'))
;

// Template UUID and Variables
$email->getHeaders()
->add(new TemplateUuidHeader('bfa432fd-0000-0000-0000-8493da283a69'))
->add(new TemplateVariableHeader('user_name', 'Jon Bush'))
->add(new TemplateVariableHeader('next_step_link', 'https://mailtrap.io/'))
->add(new TemplateVariableHeader('get_started_link', 'https://mailtrap.io/'))
->add(new TemplateVariableHeader('onboarding_video_link', 'some_video_link'))
;

$response = $mailtrap->bulkSending()->emails()->send($email);

var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
3 changes: 2 additions & 1 deletion src/Api/AbstractApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
abstract class AbstractApi
{
public const DEFAULT_HOST = 'mailtrap.io';
public const SENDMAIL_HOST = 'send.api.mailtrap.io';
public const SENDMAIL_TRANSACTIONAL_HOST = 'send.api.mailtrap.io';
public const SENDMAIL_SANDBOX_HOST = 'sandbox.api.mailtrap.io';
public const SENDMAIL_BULK_HOST = 'bulk.api.mailtrap.io';

protected ConfigInterface $config;
protected ClientInterface $httpClient;
Expand Down
7 changes: 7 additions & 0 deletions src/Api/BulkSending/BulkSendingInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Mailtrap\Api\BulkSending;

interface BulkSendingInterface
{
}
27 changes: 27 additions & 0 deletions src/Api/BulkSending/Emails.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace Mailtrap\Api\BulkSending;

use Mailtrap\Api\AbstractEmails;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Mime\Email;

/**
* Class Emails
*/
class Emails extends AbstractEmails implements BulkSendingInterface
{
public function send(Email $email): ResponseInterface
{
return $this->handleResponse(
$this->httpPost($this->getHost() . '/api/send', [], $this->getPayload($email))
);
}

protected function getHost(): string
{
return $this->config->getHost() ?: self::SENDMAIL_BULK_HOST;
}
}
2 changes: 1 addition & 1 deletion src/Api/Sending/Emails.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ public function send(Email $email): ResponseInterface

protected function getHost(): string
{
return $this->config->getHost() ?: self::SENDMAIL_HOST;
return $this->config->getHost() ?: self::SENDMAIL_TRANSACTIONAL_HOST;
}
}
12 changes: 12 additions & 0 deletions src/Bridge/Laravel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,20 @@ MAIL_MAILER="mailtrap"
MAILTRAP_HOST="send.api.mailtrap.io"
MAILTRAP_API_KEY="YOUR_API_KEY_HERE"
```
### Bulk Sending
You need to set the API key to the `MAILTRAP_API_KEY` variable.

More info about bulk sending -> https://help.mailtrap.io/article/113-sending-streams
```bash
MAIL_MAILER="mailtrap"

MAILTRAP_HOST="bulk.api.mailtrap.io"
MAILTRAP_API_KEY="YOUR_API_KEY_HERE"
```
### Sandbox
You need to set the API key to the `MAILTRAP_API_KEY` variable and set your inboxId to the `MAILTRAP_INBOX_ID`.

More info sandbox -> https://help.mailtrap.io/article/109-getting-started-with-mailtrap-email-testing
```bash
MAIL_MAILER="mailtrap"

Expand Down
11 changes: 11 additions & 0 deletions src/Bridge/Symfony/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,19 @@ MAILER_DSN=mailtrap+api://YOUR_API_KEY_HERE@default
# or
MAILER_DSN=mailtrap+api://YOUR_API_KEY_HERE@send.api.mailtrap.io
```

### Bulk Sending
Add or change MAILER_DSN variable inside your `.env` file. Also, you need to change the `YOUR_API_KEY_HERE` placeholder.

More info about bulk sending -> https://help.mailtrap.io/article/113-sending-streams
```bash
MAILER_DSN=mailtrap+api://YOUR_API_KEY_HERE@bulk.api.mailtrap.io
```

### Sandbox
Add or change MAILER_DSN variable inside your `.env` file. Also, you need to change the `YOUR_API_KEY_HERE` placeholder and put correct `inboxId`.

More info sandbox -> https://help.mailtrap.io/article/109-getting-started-with-mailtrap-email-testing
```bash
MAILER_DSN=mailtrap+api://YOUR_API_KEY_HERE@sandbox.api.mailtrap.io?inboxId=1000001
```
Expand Down
28 changes: 23 additions & 5 deletions src/Bridge/Transport/MailtrapTransportFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
use Mailtrap\Config;
use Mailtrap\Exception\RuntimeException;
use Mailtrap\MailtrapClient;
use Mailtrap\MailtrapClientInterface;
use Mailtrap\MailtrapSandboxClient;
use Mailtrap\MailtrapSendingClient;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\Mailer\Exception\UnsupportedSchemeException;
use Symfony\Component\Mailer\Transport\AbstractTransportFactory;
Expand All @@ -29,13 +29,11 @@ public function create(Dsn $dsn): TransportInterface

$inboxId = !empty($dsn->getOption('inboxId')) ? (int) $dsn->getOption('inboxId') : null;
$config = (new Config($this->getUser($dsn)))
->setHost('default' === $dsn->getHost() ? AbstractApi::SENDMAIL_HOST : $dsn->getHost())
->setHost('default' === $dsn->getHost() ? AbstractApi::SENDMAIL_TRANSACTIONAL_HOST : $dsn->getHost())
->setHttpClient(null === $this->client ? null : new Psr18Client($this->client))
;
$mailtrapClient = stripos($config->getHost(), AbstractApi::SENDMAIL_HOST) !== false
? (new MailtrapClient($config))->sending()
: (new MailtrapClient($config))->sandbox();

$mailtrapClient = $this->getMailtrapClient($config);
if ($mailtrapClient instanceof MailtrapSandboxClient && null === $inboxId) {
throw new RuntimeException(
'You cannot send email to the sandbox with empty "inboxId" param. Example -> "MAILER_DSN=mailtrap+api://APIKEY@sandbox.api.mailtrap.io?inboxId=1234"'
Expand All @@ -49,4 +47,24 @@ protected function getSupportedSchemes(): array
{
return ['mailtrap', 'mailtrap+api'];
}

private function getMailtrapClient(Config $config): MailtrapClientInterface
{
$layer = $this->determineLayerByHost($config->getHost());

return (new MailtrapClient($config))->{$layer}();
}

private function determineLayerByHost(string $host): string
{
if (stripos($host, AbstractApi::SENDMAIL_TRANSACTIONAL_HOST) !== false) {
return MailtrapClient::LAYER_TRANSACTIONAL_SENDING;
}

if (stripos($host, AbstractApi::SENDMAIL_BULK_HOST) !== false) {
return MailtrapClient::LAYER_BULK_SENDING;
}

return MailtrapClient::LAYER_SANDBOX;
}
}
19 changes: 19 additions & 0 deletions src/MailtrapBulkSendingClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace Mailtrap;

use Mailtrap\Api;

/**
* @method Api\BulkSending\Emails emails
*
* Class MailtrapBulkSendingClient
*/
final class MailtrapBulkSendingClient extends AbstractMailtrapClient
{
public const API_MAPPING = [
'emails' => Api\BulkSending\Emails::class,
];
}
19 changes: 13 additions & 6 deletions src/MailtrapClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,24 @@
/**
* The main entry point to use all possible API layers
*
* @method MailtrapGeneralClient general
* @method MailtrapSandboxClient sandbox
* @method MailtrapSendingClient sending
* @method MailtrapGeneralClient general
* @method MailtrapSandboxClient sandbox
* @method MailtrapSendingClient sending
* @method MailtrapBulkSendingClient bulkSending
*
* Class MailtrapClient
*/
class MailtrapClient extends AbstractMailtrapClient
{
public const LAYER_GENERAL = 'general';
public const LAYER_SANDBOX = 'sandbox';
public const LAYER_TRANSACTIONAL_SENDING = 'sending';
public const LAYER_BULK_SENDING = 'bulkSending';

public const API_MAPPING = [
'general' => MailtrapGeneralClient::class,
'sandbox' => MailtrapSandboxClient::class,
'sending' => MailtrapSendingClient::class,
self::LAYER_GENERAL => MailtrapGeneralClient::class,
self::LAYER_SANDBOX => MailtrapSandboxClient::class,
self::LAYER_TRANSACTIONAL_SENDING => MailtrapSendingClient::class,
self::LAYER_BULK_SENDING => MailtrapBulkSendingClient::class,
];
}
Loading

0 comments on commit b00a943

Please sign in to comment.