Skip to content

Commit

Permalink
Add Adapters and tests for Mailtrap.
Browse files Browse the repository at this point in the history
  • Loading branch information
Yash7426 committed Oct 2, 2023
1 parent 2d0f474 commit 345bd31
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 0 deletions.
73 changes: 73 additions & 0 deletions src/Utopia/Messaging/Adapters/Email/Mailtrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace Utopia\Messaging\Adapters\Email;

use Utopia\Messaging\Adapters\Email as EmailAdapter;
use Utopia\Messaging\Messages\Email;

class Mailtrap extends EmailAdapter
{
/**
* @param string $apiKey Your Mailtrap API key to authenticate with the API.
* @return void
*/
public function __construct(private string $apiKey)
{
}

/**
* Get adapter name.
*
* @return string
*/
public function getName(): string
{
return 'Mailtrap';
}

/**
* Get max messages per request.
*
* @return int
*/
public function getMaxMessagesPerRequest(): int
{
return 1000;
}

/**
* {@inheritdoc}
*
* @param Email $message
* @return string
*
* @throws Exception
*/
protected function process(Email $message): string
{
$bodyKey = $message->isHtml() ? 'html' : 'text';

$response= $this->request(
method: 'POST',
url: 'https://send.api.mailtrap.io/api/send',
headers: [
'Accept: application/json',
'Api-Token: '.$this->apiKey,
'Content-Type: application/json',
],
body: \json_encode([
'to' => \array_map(
fn ($to) => ['email' => $to],
$message->getTo()
),
"subject" =>$message->getSubject(),
$bodyKey => $message->getContent(),
'from' => [
'email' => $message->getFrom(),
],
]),
);
return $response;
}
}

36 changes: 36 additions & 0 deletions tests/e2e/Email/MailtrapTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Tests\E2E;

use Utopia\Messaging\Adapters\Email\Mailtrap;
use Utopia\Messaging\Messages\Email;

class MailtrapTest extends Base
{
/**
* @throws \Exception
*/
public function testSendPlainTextEmail()
{
$this->markTestSkipped('Mailtrap credentials not set.');

$key = getenv('MAILTAP_API_KEY');
$sender = new Mailtrap($key);

$to = getenv('TEST_EMAIL');
$subject = 'Test Subject';
$content = 'Test Content';
$from = getenv('TEST_FROM_EMAIL');

$message = new Email(
to: [$to],
from: $from,
subject: $subject,
content: $content,
);

$response = $sender->send($message);

$this->assertArrayHasKey('messageId', json_decode($response, true));
}
}

0 comments on commit 345bd31

Please sign in to comment.