diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..71c3540 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: [codenteq] \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..f5a310b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,40 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +--- +name: "πŸ› Bug Report" +about: 'Report a general issue.' +--- + +# Bug Report + + +## Issue Description + + +## Preconditions + + +## Steps To Reproduce + + +## Actual Result + + +## Expected Result + \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e5246dc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,22 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +--- +name: "πŸ’‘ Feature Request" +about: 'Share your ideas with our team or request new features' +--- \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..7763ae4 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,12 @@ +## Issue Reference + + +## Description + + +## How To Test This? + + +## Documentation +- [ ] My pull request requires an update on the documentation repository. + \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ce5adb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +vendor diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5c46118 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +CHANGELOG +========= + +0.3.0 +--- + + * Change to Symfony Azure Bridge + * New entry in config and .env file: "resource_name" and "AZURE_MAIL_RESOURCE_NAME" diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f6b4e4e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +info@arsivpro.com. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..54a6e5c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# Azure Mailer Driver Contribution Guide + +**BUGS:** + +To encourage active collaboration, eCommerce Blog Extension project encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a negative test. + +However, when filing a bug report, your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix. + +Remember, bug reports are created in the hope that others with the same problem will collaborate with you on solving it. Creating a bug report serves to help yourself and others start on the path of fixing the problem. + +**Core development ideas or discussion:** + +If you propose a new feature, please implement at least some of the code needed to complete the quality. + +Informal discussion regarding bugs, new features, and implementation of existing features occurs in the comments of the issues filed using feature template. + +**Which branch you should target?** + +All bug fixes should be sent to the latest staging branch, i.e. development branch. Bug fixes should never be sent to the master branch unless they fix features that exist only in the upcoming release. + +Minor features fully backwards compatible with the current Arduino release may be sent to the latest stable branch. + +Major new features should always be sent to the master branch, which contains the upcoming eCommerce Blog Extension release. \ No newline at end of file diff --git a/LICENSE b/LICENSE index c4f793c..a66abf8 100644 --- a/LICENSE +++ b/LICENSE @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index adcc398..595da9e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,78 @@ -# azure-mailer-driver -The Microsoft Azure ACS integration for Symfony Mailer. +# Microsoft Azure Mailer Driver + +[![Latest Stable Version](http://poser.pugx.org/codenteq/azure-mailer-driver/v)](https://packagist.org/packages/codenteq/azure-mailer-driver) +[![Total Downloads](http://poser.pugx.org/codenteq/azure-mailer-driver/downloads)](https://packagist.org/packages/codenteq/azure-mailer-driver) +[![License](http://poser.pugx.org/codenteq/azure-mailer-driver/license)](https://github.com/codenteq/azure-mailer-driver/blob/master/LICENSE) + +## 1. Introduction: + +The integration of Microsoft Azure ACS for Symfony Mailer provides a simple and clean email API supported by the [Symfony Azure Mailer Bridge](https://github.com/symfony/azure-mailer) component. + +## 2. Requirements + +* **PHP**: 8.1 or higher. +* **Composer**: 1.6.5 or higher. + +## 3. Installation + +First time using Azure ECS? Create your [Azure account](https://azure.com), if you don’t have one already. + +- Run the following command +```bash +composer require codenteq/azure-mailer-driver +``` + +### Set mail config + +> WARNING
+> It will check existence of the `config/mail.php` file, if it exists then please update the file manually with the below details. + +```php +'mailers' => [ + 'azure' => [ + 'transport' => 'azure', + 'resource_name' => env('AZURE_MAIL_RESOURCE_NAME'), + 'endpoint' => env('AZURE_MAIL_ENDPOINT', 'https://my-acs-resource-name.communication.azure.com'), + 'access_key' => env('AZURE_MAIL_KEY'), + 'api_version' => env('AZURE_MAIL_API_VERSION', '2023-03-31'), + 'disable_user_tracking' => env('AZURE_MAIL_DISABLE_TRACKING', false), + 'client' => [ + 'max_host_connections' => 10, + 'max_pending_pushes' => 100, + ] + ], +``` + +> WARNING
+> It will check existence of the .env file, if it exists then please update the file manually with the below details. + +```bash + # Mail service entries... + MAIL_MAILER=azure + + # Azure Service entries + AZURE_MAIL_RESOURCE_NAME=my-acs-resource-name + # AZURE_MAIL_ENDPOINT= #optional + AZURE_MAIL_KEY=Base64AzureAccessToken + # AZURE_MAIL_API_VERSION=2023-03-31 #optional + # AZURE_MAIL_DISABLE_TRACKING=false #optional + +``` + +> just sent your notification mail messages! + +## Available resources + +| Resource | Status | +| -------------------- | :------: | +| Plain Text | βœ… | +| HTML | βœ… | +| Attachments | βœ… | +| Multiple recipients | βœ… | +| Auth HMAC-SHA256 | βœ… | +| Notifications | βœ… | +| Mkt Campaigns | βœ… | +| Markdown | βœ… | + +## How to contribute +Azure Mailer Driver is always open for direct contributions. Contributions can be in the form of design suggestions, documentation improvements, new component suggestions, code improvements, adding new features or fixing problems. For more information please check our [Contribution Guideline document.](https://github.com/codenteq/azure-mailer-driver/blob/master/CONTRIBUTING.md) \ No newline at end of file diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 0000000..ec7139b --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,3 @@ +# Release Instructions + +[Releases](https://github.com/codenteq/azure-mailer-driver/releases) are done by [@codenteq](https://github.com/codenteq) for this repository. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..3530e7b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..52de2ee --- /dev/null +++ b/composer.json @@ -0,0 +1,54 @@ +{ + "name": "codenteq/azure-mailer-driver", + "type": "library", + "description": "The Microsoft Azure ACS integration for Symfony Mailer.", + "keywords": ["azure", "symfony", "laravel", "api", "sdk", "ecs", "mailer"], + "license": "MIT", + "homepage": "https://codenteq.com", + "minimum-stability": "stable", + "authors": [ + { + "name": "Ali Karabay", + "email": "alikarabay77@gmail.com", + "homepage": "https://github.com/karabayyazilim", + "role": "Developer" + } + ], + "support": { + "source": "https://github.com/codenteq/azure-mailer-driver", + "issues": "https://github.com/codenteq/azure-mailer-driver/issues", + "email": "info@codenteq.com" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/codenteq" + } + ], + "require": { + "php": ">=8.1", + "symfony/mailer": "^5.4.21|^6.2.7", + "symfony/http-client": "^5.4|^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.0" + }, + "conflict": { + "symfony/mime": "<6.2" + }, + "autoload": { + "psr-4": { + "Codenteq\\Azure\\Transport\\": ["src", "test"] + } + }, + "scripts": { + "test": "./vendor/bin/phpunit" + }, + "extra": { + "laravel": { + "providers": [ + "Codenteq\\Azure\\Transport\\AzureMailerServiceProvider" + ] + } + } +} diff --git a/src/AzureMailerApiTransport.php b/src/AzureMailerApiTransport.php new file mode 100644 index 0000000..3c489f2 --- /dev/null +++ b/src/AzureMailerApiTransport.php @@ -0,0 +1,409 @@ +client = $client; + $this->endpoint = $endpoint; + $this->key = $key; + $this->apiVersion = empty($apiVersion) ? self::$apiVersion : $apiVersion; + $this->disableUserEngagementTracking = !$engagementTracking; + parent::__construct($client, $dispatcher, $logger); + } + + /** + * + * @return string + */ + public function __toString(): string + { + return sprintf('azure+api://%s', $this->getAzureCSEndpoint()); + } + + /** + * Queues an email message to be sent to one or more recipients. + * + * @return ResponseInterface + */ + protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $envelope): ResponseInterface + { + + $endpointURL = $this->getEndpointRequestURL(); + $messagePayload = $this->getMessagePayload($email, $envelope); + $headers = $this->getSignedHeaders($messagePayload, $email); + + $requestOptions = [ + 'body' => json_encode($messagePayload), + 'headers' => $headers, + ]; + + $response = $this->client->request('POST', $endpointURL, $requestOptions); + + try { + $statusCode = $response->getStatusCode(); + } catch (TransportExceptionInterface $e) { + throw new HttpTransportException('Could not reach the remote Azure server.', $response, 0, $e); + } + + if (202 !== $statusCode) { + try { + $result = $response->toArray(false); + throw new HttpTransportException('Unable to send an email (' . $result['error']['code'] . '): ' . $result['error']['message'], $response, $statusCode); + } catch (DecodingExceptionInterface $e) { + throw new HttpTransportException('Unable to send an email: '.$response->getContent(false).sprintf(' (code %d).', $statusCode), $response, 0, $e); + } + } + + $sentMessage->setMessageId(json_decode($response->getContent(false), true)['id']); + + return $response; + } + + /** + * Get the message request body + * + * @param Email $email + * @param Envelope $envelope + * @return array + */ + private function getMessagePayload(Email $email, Envelope $envelope): array + { + $addressStringifier = function (Address $address) { + $stringified = ['address' => $address->getAddress()]; + + if ($address->getName()) { + $stringified['displayName'] = $address->getName(); + } + + return $stringified; + }; + + $data = [ + 'content' => [ + 'html' => $email->getHtmlBody(), + 'plainText' => $email->getTextBody(), + 'subject' => $email->getSubject(), + ], + 'recipients' => [ + 'to' => array_map($addressStringifier, $this->getRecipients($email, $envelope)), + ], + 'senderAddress' => $envelope->getSender()->getAddress(), + 'attachments' => $this->getMessageAttachments($email), + 'userEngagementTrackingDisabled' => $this->getDisableUserEngagementTracking(), + 'headers' => empty($headers = $this->getMessageCustomHeaders($email)) ? null : $headers, + 'importance' => $this->getPriorityLevel($email->getPriority()), + ]; + + if ($emails = array_map($addressStringifier, $email->getCc())) { + $data['recipients']['cc'] = $emails; + } + + if ($emails = array_map($addressStringifier, $email->getBcc())) { + $data['recipients']['bcc'] = $emails; + } + + if ($emails = array_map($addressStringifier, $email->getReplyTo())) { + $data['replyTo'] = $emails; + } + + return $data; + } + + /** + * List of attachments. Please note that we limit the total size of + * an email request (which includes attachments) to 10MB. + * + * @param Email $email + * @return array + */ + private function getMessageAttachments(Email $email): array + { + $attachments = []; + foreach ($email->getAttachments() as $attachment) { + $headers = $attachment->getPreparedHeaders(); + $filename = $headers->getHeaderParameter('Content-Disposition', 'filename'); + $disposition = $headers->getHeaderBody('Content-Disposition'); + + $att = [ + 'name' => $filename, + 'contentInBase64' => base64_encode(str_replace("\r\n", '', $attachment->bodyToString())), + 'contentType' => $headers->get('Content-Type')->getBody(), + ]; + + if ('inline' === $disposition) { + $att['content_id'] = $filename; + } + + $attachments[] = $att; + } + + return $attachments; + } + + /** + * Version of ACS API to invoke. + * + * @return string + */ + private function getApiVersion(): string + { + return $this->apiVersion; + } + + /** + * The communication request path with query string, for example /emails:send?api-version=2023-03-31 + * + * @return string + */ + private function getURIPathAndQuery(): string + { + return '/emails:send?api-version=' . $this->getApiVersion(); + } + + /** + * The communication resource, for example https://my-acs-resource.communication.azure.com + * + * @return string + */ + private function getEndpointRequestURL(): string + { + return $this->getAzureCSEndpoint() . $this->getURIPathAndQuery(); + } + + /** + * The communication domain host, for example my-acs-resource.communication.azure.com + * + * @return string + */ + private function getAzureCSEndpoint(): string + { + return ($this->endpoint ?: self::HOST); + } + + /** + * Get name and email from contact list + * + * @param array $contacs + * @return array + */ + private function getContactNameAndEmail($contacts): array + { + $formatted = []; + if (empty($contacts)) { + return []; + } + foreach ($contacts as $address => $display) { + $formatted[] = array_filter([ + 'displayName' => $display, + 'email' => $address, + ]); + } + return $formatted; + } + + /** + * Generate hash from message content + * + * @param string $content + * @return string + */ + private function getContentHash(string $content): string + { + //$data = mb_convert_encoding($content, 'UTF-8'); + $hash = hash('sha256', $content, true); + //return base64 hash + return base64_encode($hash); + } + + /** + * Generate sha256 hash and encode to base64 to produces the digest string. + * + * @return string + */ + private function getAuthenticationSignature(string $content): string + { + //dd($content); + $key = base64_decode($this->key); + $hashedBytes = hash_hmac('sha256', mb_convert_encoding($content, 'UTF-8'), $key, true); + return base64_encode($hashedBytes); + } + + /** + * Get authenticated headers for signed request, + * + * @return array + */ + private function getSignedHeaders(array $payload, Email $message): array + { + //HTTP Method verb (uppercase) + $verb = "POST"; + + //Request time + $datetime = new \DateTime("now", new \DateTimeZone("UTC")); + $utcNow = $datetime->format('D, d M Y H:i:s \G\M\T'); + + //Content hash signature + $contentHash = $this->getContentHash(json_encode($payload)); + + //ACS Endpoint + $host = str_replace('https://', '', $this->endpoint); + + //Sendmail endpoint from communication email delivery service + $urlPathAndQuery = '/emails:send?api-version=' . $this->getApiVersion(); + + //Signed request headers + $stringToSign = "{$verb}\n{$urlPathAndQuery}\n{$utcNow};{$host};{$contentHash}"; + + //Authenticate headers with ACS primary or secondary key + $signature = $this->getAuthenticationSignature($stringToSign); + + //get GUID part of message id to identify the long running operation + //$messageId = explode('@', $message->generateMessageId(), 2)[0]; + + $messageId = $this->generateMessageId(); + + $headers = [ + 'Content-Type' => 'application/json', + 'repeatability-request-id' => $messageId, + 'Operation-Id' => $messageId, + 'repeatability-first-sent' => $utcNow, + 'x-ms-date' => $utcNow, + 'x-ms-content-sha256' => $contentHash, + 'x-ms-client-request-id' => $messageId, + "Authorization" => "HMAC-SHA256 SignedHeaders=x-ms-date;host;x-ms-content-sha256&Signature={$signature}", + ]; + + //return signed headers to http client request + return $headers; + } + + /** + * Identify the long running operation. + * + * @return array + */ + private function generateMessageId(): string + { + $data = random_bytes(16); + assert(strlen($data) == 16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); + + // Output the 36 character UUID. + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); + } + + /** + * Custom email headers to be passed. + * + * @return array + */ + private function getMessageCustomHeaders(Email $email): array + { + + $headers = []; + + $headersToBypass = ['x-ms-client-request-id', 'operation-id', 'authorization', 'x-ms-content-sha256', 'received', 'dkim-signature', 'content-transfer-encoding', 'from', 'to', 'cc', 'bcc', 'subject', 'content-type', 'reply-to']; + + foreach ($email->getHeaders()->all() as $name => $header) { + if (\in_array($name, $headersToBypass, true)) { + continue; + } + $headers[$header->getName()] = $header->getBodyAsString(); + } + + return $headers; + } + + /** + * Get the message priority level + * + * @return string + */ + private function getPriorityLevel($priority): ?string + { + return strtolower([ + Email::PRIORITY_HIGHEST => 'Highest', + Email::PRIORITY_HIGH => 'High', + Email::PRIORITY_NORMAL => 'Normal', + Email::PRIORITY_LOW => 'Low', + Email::PRIORITY_LOWEST => 'Lowest', + ][$priority]); + } + + /** + * Indicates whether user engagement tracking should be disabled. + * + * @return bool + */ + private function getDisableUserEngagementTracking(): bool + { + return $this->disableUserEngagementTracking; + } +} diff --git a/src/AzureMailerManager.php b/src/AzureMailerManager.php new file mode 100644 index 0000000..091ef05 --- /dev/null +++ b/src/AzureMailerManager.php @@ -0,0 +1,21 @@ +app['config']->get('mail.mailers.azure', []); + + return new AzureMailerApiTransport( + $config['endpoint'], + $config['access_key'], + $config['api_version'], + boolval($config['disable_user_tracking']), + $this->getHttpClient($config), + ); + } +} diff --git a/src/AzureMailerServiceProvider.php b/src/AzureMailerServiceProvider.php new file mode 100644 index 0000000..e61e9da --- /dev/null +++ b/src/AzureMailerServiceProvider.php @@ -0,0 +1,41 @@ +app->singleton('mail.manager', function($app) { + return new AzureMailerManager($app); + }); + + $this->app->bind('mailer', function ($app) { + return $app->make('mail.manager')->mailer(); + }); + + $this->app->extend('azure', function ($app) { + return $app->make('mail.manager')->mailer(); + }); + + $this->app->extend('azure', function () { + return (new AzureMailerTransportFactory)->create( + new Dsn( + 'azure+api', + config('mail.mailers.azure.endpoint'), + config('mail.mailers.azure.access_key'), + config('mail.mailers.azure.api_version'), + config('mail.mailers.azure.disable_user_tracking') + ) + ); + }); + } +} diff --git a/src/AzureMailerTransportFactory.php b/src/AzureMailerTransportFactory.php new file mode 100644 index 0000000..e435fee --- /dev/null +++ b/src/AzureMailerTransportFactory.php @@ -0,0 +1,41 @@ +getScheme(); + $endpoint = $dsn->getHost(); + $key = $this->getPassword($dsn); + $apiVersion = $this->getApiVersion($dsn); + $engagementTracking = $this->getEngagementTracking($dsn); + + if ('azure+api' === $scheme || 'azure' === $scheme) { + return new AzureMailerApiTransport($endpoint, $key, $apiVersion, $engagementTracking, $this->client, $this->dispatcher, $this->logger); + } + + throw new UnsupportedSchemeException($dsn, 'azure', $this->getSupportedSchemes()); + } + + protected function getSupportedSchemes(): array + { + return ['azure', 'azure+api']; + } + + protected function getApiVersion(Dsn $dsn): string + { + return $dsn->getOption('api-version', '2023-03-31'); + } + + protected function getEngagementTracking(Dsn $dsn): bool + { + return boolval($dsn->getOption('tracking', false)); + } +} diff --git a/test/AzureMailerApiTransportTest.php b/test/AzureMailerApiTransportTest.php new file mode 100644 index 0000000..abc0e9e --- /dev/null +++ b/test/AzureMailerApiTransportTest.php @@ -0,0 +1,252 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Codenteq\Azure\Transport; + +use Codenteq\Azure\Transport\AzureMailerApiTransport; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Mailer\Envelope; +use Symfony\Component\Mailer\Header\MetadataHeader; +use Symfony\Component\Mailer\Header\TagHeader; +use Symfony\Component\Mime\Address; +use Symfony\Component\Mime\Email; +use Symfony\Component\Mime\Part\DataPart; +use Symfony\Contracts\HttpClient\HttpClientInterface; +use Symfony\Contracts\HttpClient\ResponseInterface; + +class AzureMailerApiTransportTest extends TestCase +{ + /** + * @dataProvider getTransportData + */ + public function testToString(AzureMailerApiTransport $transport, string $expected) + { + $this->assertSame($expected, (string) $transport); + } + + public static function getTransportData() + { + return [ + [ + new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'), + 'azure+api://my-acs-resource.communication.azure.com', + ], + [ + (new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'))->setHost('my-acs-resource.communication.azure.com'), + 'azure+api://my-acs-resource.communication.azure.com', + ], + [ + (new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'))->setHost('my-acs-resource.communication.azure.com')->setPort(99), + 'azure+api://my-acs-resource.communication.azure.com:99', + ], + ]; + } + + public function testSend() + { + $email = new Email(); + $email->from(new Address('foo@example.com', 'Ms. Foo Bar')) + ->to(new Address('bar@example.com', 'Mr. Recipient')) + ->bcc('baz@example.com') + ->text('content'); + + $response = $this->createMock(ResponseInterface::class); + + $response + ->expects($this->once()) + ->method('getStatusCode') + ->willReturn(202); + $response + ->expects($this->once()) + ->method('getHeaders') + ->willReturn(['x-message-id' => '1']); + + $httpClient = $this->createMock(HttpClientInterface::class); + + $httpClient + ->expects($this->once()) + ->method('request') + ->with('POST', 'https://my-acs-resource.communication.azure.com/emails:send?api-version=2023-03-31', [ + 'body' => [ + 'personalizations' => [ + [ + 'to' => [[ + 'email' => 'bar@example.com', + 'name' => 'Mr. Recipient', + ]], + 'subject' => null, + 'bcc' => [['email' => 'baz@example.com']], + ], + ], + 'from' => [ + 'email' => 'foo@example.com', + 'name' => 'Ms. Foo Bar', + ], + 'content' => [ + ['type' => 'text/plain', 'value' => 'content'], + ], + ], + 'headers' => [ + 'Authorization' => 'foo' + ], + ]) + ->willReturn($response); + + $mailer = new AzureMailerApiTransport('foo', $httpClient); + $mailer->send($email); + } + + public function testLineBreaksInEncodedAttachment() + { + $email = new Email(); + $email->from('foo@example.com') + ->to('bar@example.com') + // even if content doesn't include new lines, the base64 encoding performed later may add them + ->addPart(new DataPart('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod', 'lorem.txt')); + + $response = $this->createMock(ResponseInterface::class); + + $response + ->expects($this->once()) + ->method('getStatusCode') + ->willReturn(202); + $response + ->expects($this->once()) + ->method('getHeaders') + ->willReturn(['operation-id' => '1']); + + $httpClient = $this->createMock(HttpClientInterface::class); + + $httpClient + ->expects($this->once()) + ->method('request') + ->with('POST', 'https://my-acs-resource.communication.azure.com/emails:send?api-version=2023-03-31', [ + 'body' => [ + 'personalizations' => [ + [ + 'to' => [['email' => 'bar@example.com']], + 'subject' => null, + ], + ], + 'from' => ['email' => 'foo@example.com'], + 'content' => [], + 'attachments' => [ + [ + 'content' => 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdCwgc2VkIGRvIGVpdXNtb2Q=', + 'filename' => 'lorem.txt', + 'type' => 'application/octet-stream', + 'disposition' => 'attachment', + ], + ], + ], + 'headers' => [ + 'Authorization' => 'foo' + ], + ]) + ->willReturn($response); + + $mailer = new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING', $httpClient); + + $mailer->send($email); + } + + public function testCustomHeader() + { + $email = new Email(); + $email->getHeaders()->addTextHeader('foo', 'bar'); + $envelope = new Envelope(new Address('alice@system.com'), [new Address('bob@system.com')]); + + $transport = new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'); + $method = new \ReflectionMethod(AzureMailerApiTransport::class, 'getPayload'); + $payload = $method->invoke($transport, $email, $envelope); + + $this->assertArrayHasKey('headers', $payload); + $this->assertArrayHasKey('foo', $payload['headers']); + $this->assertEquals('bar', $payload['headers']['foo']); + } + + public function testReplyTo() + { + $from = 'from@example.com'; + $to = 'to@example.com'; + $replyTo = 'replyto@example.com'; + $email = new Email(); + $email->from($from) + ->to($to) + ->replyTo($replyTo) + ->text('content'); + $envelope = new Envelope(new Address($from), [new Address($to)]); + + $transport = new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'); + $method = new \ReflectionMethod(AzureMailerApiTransport::class, 'getPayload'); + $payload = $method->invoke($transport, $email, $envelope); + + $this->assertArrayHasKey('from', $payload); + $this->assertArrayHasKey('email', $payload['from']); + $this->assertSame($from, $payload['from']['email']); + + $this->assertArrayHasKey('reply_to', $payload); + $this->assertArrayHasKey('email', $payload['reply_to']); + $this->assertSame($replyTo, $payload['reply_to']['email']); + } + + public function testEnvelopeSenderAndRecipients() + { + $from = 'from@example.com'; + $to = 'to@example.com'; + $envelopeFrom = 'envelopefrom@example.com'; + $envelopeTo = 'envelopeto@example.com'; + $email = new Email(); + $email->from($from) + ->to($to) + ->cc('cc@example.com') + ->bcc('bcc@example.com') + ->text('content'); + $envelope = new Envelope(new Address($envelopeFrom), [new Address($envelopeTo)]); + + $transport = new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'); + $method = new \ReflectionMethod(AzureMailerApiTransport::class, 'getPayload'); + $payload = $method->invoke($transport, $email, $envelope); + + $this->assertArrayHasKey('from', $payload); + $this->assertArrayHasKey('email', $payload['from']); + $this->assertSame($envelopeFrom, $payload['from']['email']); + + $this->assertArrayHasKey('personalizations', $payload); + $this->assertArrayHasKey('to', $payload['personalizations'][0]); + $this->assertArrayHasKey('email', $payload['personalizations'][0]['to'][0]); + $this->assertCount(1, $payload['personalizations'][0]['to']); + $this->assertSame($envelopeTo, $payload['personalizations'][0]['to'][0]['email']); + } + + public function testTagAndMetadataHeaders() + { + $email = new Email(); + $email->getHeaders()->add(new TagHeader('category-one')); + $email->getHeaders()->add(new MetadataHeader('Color', 'blue')); + $email->getHeaders()->add(new MetadataHeader('Client-ID', '12345')); + $envelope = new Envelope(new Address('alice@system.com'), [new Address('bob@system.com')]); + + $transport = new AzureMailerApiTransport('ENDPOINT', 'KEY', 'API_VERSION', 'ENGAGEMENT_TRACKING'); + $method = new \ReflectionMethod(AzureMailerApiTransport::class, 'getPayload'); + $payload = $method->invoke($transport, $email, $envelope); + + $this->assertArrayHasKey('categories', $payload); + $this->assertArrayHasKey('custom_args', $payload['personalizations'][0]); + + $this->assertCount(1, $payload['categories']); + $this->assertCount(2, $payload['personalizations'][0]['custom_args']); + + $this->assertSame(['category-one'], $payload['categories']); + $this->assertSame('blue', $payload['personalizations'][0]['custom_args']['Color']); + $this->assertSame('12345', $payload['personalizations'][0]['custom_args']['Client-ID']); + } +} diff --git a/test/AzureMailerTransportFactoryTest.php b/test/AzureMailerTransportFactoryTest.php new file mode 100644 index 0000000..961e80d --- /dev/null +++ b/test/AzureMailerTransportFactoryTest.php @@ -0,0 +1,75 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + + namespace Codenteq\Azure\Transport; + +use Codenteq\Azure\Transport\AzureMailerApiTransport; +use Codenteq\Azure\Transport\AzureMailerTransportFactory; +use Psr\Log\NullLogger; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\Mailer\Test\TransportFactoryTestCase; +use Symfony\Component\Mailer\Transport\Dsn; +use Symfony\Component\Mailer\Transport\TransportFactoryInterface; + +class AzureMailerTransportFactoryTest extends TransportFactoryTestCase +{ + public function getFactory(): TransportFactoryInterface + { + return new AzureMailerTransportFactory(null, new MockHttpClient(), new NullLogger()); + } + + public static function supportsProvider(): iterable + { + yield [ + new Dsn('azure+api', 'default'), + true, + ]; + + yield [ + new Dsn('azure', 'default'), + true, + ]; + } + + public static function createProvider(): iterable + { + $logger = new NullLogger(); + + yield [ + new Dsn('azure+api', 'default', self::USER), + new AzureMailerApiTransport(self::USER, new MockHttpClient(), null, $logger), + ]; + + yield [ + new Dsn('azure+api', 'example.com', self::USER, '', 8080), + (new AzureMailerApiTransport(self::USER, new MockHttpClient(), null, $logger))->setHost('example.com')->setPort(8080), + ]; + + yield [ + new Dsn('azure', 'default', self::USER), + new AzureMailerApiTransport(self::USER, null, $logger), + ]; + + } + + public static function unsupportedSchemeProvider(): iterable + { + yield [ + new Dsn('azure+foo', 'azure', self::USER), + 'The "azure+foo" scheme is not supported; supported schemes for mailer "azure" are: "azure", "azure+api".', + ]; + } + + public static function incompleteDsnProvider(): iterable + { + yield [new Dsn('azure+api', 'default')]; + } +}