diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..9652006 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -50,6 +50,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..2763b9c 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..efdd72e 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { - "backwardCompatibilityCheck": true + "ignore_php_platform_requirements": { + "8.6": true + }, + "backwardCompatibilityCheck": false } diff --git a/CHANGELOG.md b/CHANGELOG.md index 382f245..7d0ae49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,418 +1,1217 @@ +# Changelog + +## 6.0.0 - Unreleased + +### Changed + +- **BC:** mail services are configured under `dot_mail.services`; `dot_mail.log` stays separate. A configuration in the old layout (`dot_mail.default`) now fails with an `InvalidArgumentException`. Move the service blocks as shown in `config/mail.global.php.dist`. +- **BC:** `send()` restores the configured defaults after every attempt, successful or not: recipients, subject, body and attachments must be set again for every message. `getMessage()` returns a new object after each send. +- **BC:** a missing or unreadable attachment now throws a `MailException` instead of being skipped. +- **BC:** the attachment directory (`attachments.dir`) is scanned at send time instead of once at start-up, and files and directories starting with a dot are skipped. Attachments are read with `DataPart::fromPath()`, so no file handles are left open. +- **BC:** `send()` handles any `Throwable`, and the `MailException` it throws carries the original exception and code. `ResultInterface`, `MailResult` and `createMailResultFromException()` use `Throwable` instead of `Exception`. +- **BC:** an exception thrown by a post-send listener propagates unchanged and is no longer reported as a send error, because the message was already delivered. +- **BC:** the `esmtp` transport is built directly from `smtp_options` instead of through a DSN string. Credentials with special characters work, empty credentials are not sent, and `smtp_options.name` and `connection_time_limit` now take effect. `SmtpOptions::getName()` returns `?string` and defaults to `null`. +- **BC:** a transport object or container service provided in `transport` is used as given and no longer replaced. +- **BC:** `sendmail` is the default transport when the `transport` key is omitted, matching `config/mail.global.php.dist` and the documentation. +- **BC:** `MailEvent::getResult()` returns `?ResultInterface`; the result is `null` in the pre-send event. +- **BC:** a message that never received a body fails validation instead of being sent empty; an empty `body.content` in the configuration is no longer applied. +- **BC:** the charset passed to `setBody()` and `body.charset` are used; `send()` only sets `utf-8` when no encoding is set. +- **BC:** the minimum supported PHP version is 8.3 (`~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0`). +- **BC:** mail services are created by `MailServiceFactory` and `MailOptionsFactory`, which work with any PSR-11 container. `dot-mail.service.default` and `dot-mail.options.default` are registered by `ConfigProvider`; any other mail service must be registered by the application, for example `'dot-mail.service.newsletter' => MailServiceFactory::class`. +- **BC:** requesting a mail service that is not configured under `dot_mail.services` throws an `InvalidArgumentException`. +- **BC:** `MailServiceInterface::setBody()` accepts `string|AbstractPart`; implementations must widen the parameter. +- **BC:** `MailEvent` extends `Laminas\EventManager\Event` instead of `Dot\Event\Event`. +- **BC:** `Email::setSender()` takes `Address|string $address` and `?string $name`; the first parameter was named `$addresses`. +- PHPUnit 12, PHPStan level 8, and newer GitHub Actions versions (`actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7`). +- A failing log write no longer turns a delivered email into an error; `LogService::sent()` returns `false` when the log directory cannot be created, and writes use `LOCK_EX`. +- Option getters fall back to defaults, so a minimal configuration no longer fails with uninitialized properties. + +### Added + +- `MailServiceInterface::reset()`, which restores the configured message and attachments. The `MailService` constructor accepts the default attachments as an optional fifth argument. +- `MailServiceInterface` is aliased to `dot-mail.service.default`, so it can be injected by interface. +- PHP 8.6 in the version constraint and in the CI matrix. +- `laminas/laminas-stdlib`, `laminas/laminas-eventmanager` and `psr/container` as direct dependencies. + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.2. +- Unused attachment handling code from `Dot\Mail\Email`. +- **BC:** `AbstractMailFactory`, `MailServiceAbstractFactory` and `MailOptionsAbstractFactory`, and the `abstract_factories` entry in `ConfigProvider`. +- The `laminas/laminas-servicemanager` requirement. Applications using Laminas Service Manager require it themselves. +- The `dotkernel/dot-event` requirement. + +### Fixed + +- `Email::addTo()` and the other address methods accept arrays of `Address` objects. +- Transport aliases are matched case-insensitively (`ESMTP`, `SendMail`). +- Missing `username`, `password` or `tls` keys in `smtp_options.connection_config` no longer raise warnings, and credentials with special characters work. +- Detaching a listener that was never attached no longer removes a wrong entry. +- Error messages for an invalid transport, an invalid event listener and an invalid port are accurate. +- `Email::setSender()` accepts an `Address` object. +- A body set as a MIME part (`setBody(AbstractPart)`) is sent instead of failing validation. +- Files inside hidden directories of the attachments directory are no longer attached. +- An invalid `event_listeners` entry throws a `RuntimeException` instead of a `TypeError`. +- `config/mail.global.php.dist` sets `smtp_options.host` to `127.0.0.1` instead of an empty string. + +## 5.4.3 - 2026-05-11 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Attachments of a failed send no longer leak into the next email; the message body is reset after every send attempt ([#115](https://github.com/dotkernel/dot-mail/pull/115)) + +## 5.4.2 - 2026-03-03 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- `MailService`: fixed the email structure when sending multiple attachments ([#113](https://github.com/dotkernel/dot-mail/pull/113)) + +## 5.4.1 - 2025-11-12 + +### Changed + +- Updated OSS lifecycle metadata ([#111](https://github.com/dotkernel/dot-mail/pull/111)) +- Updated readme and documentation ([#112](https://github.com/dotkernel/dot-mail/pull/112)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 5.4.0 - 2025-11-03 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.4 and 8.5 ([#104](https://github.com/dotkernel/dot-mail/pull/104)) + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.1 ([#104](https://github.com/dotkernel/dot-mail/pull/104)) + +### Fixed + +- Linking between documentation versions ([#105](https://github.com/dotkernel/dot-mail/pull/105)) + +## 5.1.6 - 2025-11-03 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.4 and 8.5 ([#103](https://github.com/dotkernel/dot-mail/pull/103)) + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.1 ([#103](https://github.com/dotkernel/dot-mail/pull/103)) + +### Fixed + +- Nothing + +## 5.0.4 - 2025-11-03 + +### Changed + +- Documentation: version `5.0` is the default ([#75](https://github.com/dotkernel/dot-mail/pull/75)) +- Updated the v5 documentation ([#78](https://github.com/dotkernel/dot-mail/pull/78)) +- Bumped Psalm to 6.x ([#84](https://github.com/dotkernel/dot-mail/pull/84)) + +### Added + +- Support for `laminas/laminas-servicemanager` 4.x ([#82](https://github.com/dotkernel/dot-mail/pull/82)) +- Upgrade guide from v4 to v5 ([#81](https://github.com/dotkernel/dot-mail/pull/81)) +- Support for PHP 8.4 and 8.5 ([#102](https://github.com/dotkernel/dot-mail/pull/102)) + +### Deprecated + +- Nothing + +### Removed + +- Unused code inherited from version 4.0 ([#73](https://github.com/dotkernel/dot-mail/pull/73)) +- Support for PHP 8.1 ([#102](https://github.com/dotkernel/dot-mail/pull/102)) + +### Fixed + +- Version links in the documentation footer ([#80](https://github.com/dotkernel/dot-mail/pull/80)) +- Attachments not working ([#87](https://github.com/dotkernel/dot-mail/pull/87)) + +## 5.3.0 - 2025-03-04 + +### Changed + +- Replaced Psalm with PHPStan ([#90](https://github.com/dotkernel/dot-mail/pull/90)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Unused code ([#97](https://github.com/dotkernel/dot-mail/pull/97)) + +### Fixed + +- Error caused by special characters ([#94](https://github.com/dotkernel/dot-mail/pull/94)) + +## 5.1.5 - 2025-02-28 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Error caused by special characters in the password ([#95](https://github.com/dotkernel/dot-mail/pull/95)) + +## 5.1.4 - 2025-02-17 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Attachments not working ([#88](https://github.com/dotkernel/dot-mail/pull/88)) + +## 5.2.2 - 2025-02-14 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Attachments not working ([#87](https://github.com/dotkernel/dot-mail/pull/87)) + +## 5.2.1 - 2025-01-28 + +### Changed + +- Bumped Psalm to 6.x ([#84](https://github.com/dotkernel/dot-mail/pull/84)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 5.2.0 - 2025-01-13 + +### Changed + +- Nothing + +### Added + +- Support for `laminas/laminas-servicemanager` 4.x ([#82](https://github.com/dotkernel/dot-mail/pull/82)) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 5.1.3 - 2025-01-06 + +### Changed + +- Nothing + +### Added + +- Upgrade guide from v4 to v5 ([#81](https://github.com/dotkernel/dot-mail/pull/81)) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 5.1.2 - 2024-12-19 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Version links in the documentation footer ([#80](https://github.com/dotkernel/dot-mail/pull/80)) + +## 5.1.1 - 2024-12-19 + +### Changed + +- Documentation: version `5.0` is the default ([#75](https://github.com/dotkernel/dot-mail/pull/75)) +- Updated the v5 documentation ([#78](https://github.com/dotkernel/dot-mail/pull/78)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 5.1.0 - 2024-12-06 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Unused code inherited from version 4.0 ([#73](https://github.com/dotkernel/dot-mail/pull/73)) + +### Fixed + +- Nothing + +## 5.0.3 - 2024-12-03 + +### Changed + +- Added `declare(strict_types=1)` to the configuration file ([#69](https://github.com/dotkernel/dot-mail/pull/69)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 5.0.2 - 2024-11-19 + +### Changed + +- Cleaned the configuration file ([#67](https://github.com/dotkernel/dot-mail/pull/67)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- The "from" name is displayed correctly ([#67](https://github.com/dotkernel/dot-mail/pull/67)) + +## 5.0.1 - 2024-11-18 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- SMTP transport: missing `port` array key ([#66](https://github.com/dotkernel/dot-mail/pull/66)) + +## 5.0.0 - 2024-11-15 + +### Changed + +- Replaced `laminas-mail` with `symfony/mailer` ([#65](https://github.com/dotkernel/dot-mail/pull/65)) +- Updated readme ([#61](https://github.com/dotkernel/dot-mail/pull/61)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- `mime` and `imap` related functionality (see the upgrade guide from v4 to v5) + +### Fixed + +- Nothing + +## 4.3.0 - 2024-10-28 + +### Changed + +- Final release of the wrapper over `laminas-mail` +- Updated readme ([#61](https://github.com/dotkernel/dot-mail/pull/61)) +- Locked PHP at version 8.3 ([#64](https://github.com/dotkernel/dot-mail/pull/64)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 4.2.2 - 2024-06-28 + +### Changed + +- Updated the documentation overview ([#59](https://github.com/dotkernel/dot-mail/pull/59)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 4.2.1 - 2024-06-18 + +### Changed + +- Updated the documentation overview ([#58](https://github.com/dotkernel/dot-mail/pull/58)) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 4.2.0 - 2024-05-03 + +### Changed + +- Updated workflows ([#55](https://github.com/dotkernel/dot-mail/pull/55)) + +### Added + +- v4 documentation ([#55](https://github.com/dotkernel/dot-mail/pull/55)) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 4.1.1 - 2023-11-29 + +### Changed + +- Bumped PHP to 8.3 ([#53](https://github.com/dotkernel/dot-mail/pull/53)) + +### Added + +- Codecov badge ([#51](https://github.com/dotkernel/dot-mail/pull/51)) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 4.1.0 - 2023-08-08 + +### Changed + +- Psalm and phpcs fixes ([#47](https://github.com/dotkernel/dot-mail/pull/47)) + +### Added + +- PHPUnit and tests ([#47](https://github.com/dotkernel/dot-mail/pull/47)) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 4.0.4 - 2022-09-28 + +### Changed + +- Updated error reporting + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.4.6 - 2022-09-28 + +### Changed + +- Updated error reporting + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + ## 4.0.3 - 2022-08-31 ### Changed -* Improved email storage handling -* Updated readme + +- Improved email storage handling +- Updated readme ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 4.0.2 - 2022-08-23 ### Changed -* Updated mail.global.php.dist + +- Updated mail.global.php.dist ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 4.0.1 - 2022-08-12 ### Changed -* Updated readme -* Updated mail.global.php.dist + +- Updated readme +- Updated mail.global.php.dist ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 4.0.0 - 2022-08-11 ### Changed -* Updated dependecies versions, including PHP to ~8.0.0 || ~8.1.0 -* Restricted laminas-mail version to >=2.17 + +- Updated dependecies versions, including PHP to ~8.0.0 || ~8.1.0 +- Restricted laminas-mail version to >=2.17 ### Added -* Saving outgoing emails into folders + +- Saving outgoing emails into folders ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.4.5 - 2022-08-30 ### Changed -* Updated readme + +- Updated readme ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.4.4 - 2022-08-26 ### Changed -* Nothing + +- Nothing ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Updated check for storage + +- Updated check for storage ## 3.4.3 - 2022-08-25 ### Changed -* Improved email storage handling + +- Improved email storage handling ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.4.2 - 2022-08-23 ### Changed -* Updated mail.global.php.dist + +- Updated mail.global.php.dist ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.4.1 - 2022-08-12 ### Changed -* Nothing + +- Nothing ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* laminas/laminas-dependency-plugin + +- laminas/laminas-dependency-plugin ### Fixed -* Nothing + +- Nothing ## 3.4.0 - 2022-08-10 ### Changed -* Nothing + +- Nothing ### Added -* Saving outgoing emails into folders + +- Saving outgoing emails into folders ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.3.1 - 2022-08-10 ### Changed -* Updated dependecies versions -* Restricted laminas-mail version to <=2.16 + +- Updated dependecies versions +- Restricted laminas-mail version to <=2.16 ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.3.0 - 2022-06-20 ### Changed -* Updated PHP version to allow 8.0 and 8.1 + +- Updated PHP version to allow 8.0 and 8.1 ### Added -* PHP 8.0 and 8.1 compatiblity + +- PHP 8.0 and 8.1 compatiblity ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 2.1 - 2021-11-04 ### Changed -* Nothing + +- Nothing ### Added -* Logging sent emails + +- Logging sent emails ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.2.1 - 2021-09-24 ### Changed -* Nothing + +- Nothing ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* log/mail directory privileges + +- log/mail directory privileges ## 3.2.0 - 2021-09-23 ### Changed -* Nothing + +- Nothing ### Added -* Logging sent emails + +- Logging sent emails ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing ## 3.1.1 - 2021-06-08 ### Changed -* Nothing + +- Nothing ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* fix issue #9: UTF-8 characters in message body + +- fix issue #9: UTF-8 characters in message body ## 3.1.0 - 2020-11-03 ### Changed -* Composer 2 compatibility. -* Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. + +- Composer 2 compatibility. +- Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. ### Added -* bump min version of laminas/laminas-mail + +- bump min version of laminas/laminas-mail ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* bump min version of laminas/laminas-dependency-plugin -* bump min version of dotkernel/dot-event + +- bump min version of laminas/laminas-dependency-plugin +- bump min version of dotkernel/dot-event ## 2.0.0 - 2020-01-30 ### Changed -* Laminas and Mezzio migration. + +- Laminas and Mezzio migration. ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Support + +- Support ### Fixed -* Nothing +- Nothing ## 1.0.0 - 2018-10-05 ### Changed -* Nothing + +- Nothing ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* TemplateRendererInterface requirement -* Templating in mail support + +- TemplateRendererInterface requirement +- Templating in mail support ### Fixed -* Nothing +- Nothing ## 0.2.0 - 2018-05-14 ### Changed -* updated `dot-twigrenderer` dependency + +- updated `dot-twigrenderer` dependency ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.3 - 2017-04-21 ### Changed -* send mail does not rethrow exceptions anymore + +- send mail does not rethrow exceptions anymore ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.2 - 2017-03-16 ### Changed -* updated composer.json + +- updated composer.json ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.1 - 2017-03-11 Updated php file headers doc blocks ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.0 - 2017-03-09 Initial tagged release ### Added -* Everything + +- Everything ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing diff --git a/README.md b/README.md index f3913d7..c250d8f 100644 --- a/README.md +++ b/README.md @@ -10,26 +10,27 @@ Documentation is available at: https://docs.dotkernel.org/dot-mail/. ## Version History -| Branch | Release | PSR-11 | Mailer | OSS Lifecycle | PHP Version | -|--------|------------|----------|------------------|-------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| -| 5.2 | `>=5.2.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.2%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.4.0) | -| 5.1 | `<5.2.0` | 1 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.1%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.1.6) | -| 5.0 | `<5.1.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.0.4) | -| 4.0 | `<=4.3.0` | 1 | `laminas-mail` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F4.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/4.3.0) | +| Branch | Release | PSR-11 | Mailer | OSS Lifecycle | PHP Version | +|--------|------------------|----------|------------------|-------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| +| 6.0 | `>=6.0.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F6.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/6.0.0) | +| 5.2 | `>=5.2.0 <6.0.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.2%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.4.0) | +| 5.1 | `<5.2.0` | 1 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.1%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.1.6) | +| 5.0 | `<5.1.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.0.4) | +| 4.0 | `<=4.3.0` | 1 | `laminas-mail` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F4.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/4.3.0) | ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-mail) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.4.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/6.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/blob/5.2/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/blob/6.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-mail/actions/workflows/continuous-integration.yml/badge.svg?branch=5.2)](https://github.com/dotkernel/dot-mail/actions/workflows/continuous-integration.yml) -[![codecov](https://codecov.io/gh/dotkernel/dot-mail/branch/5.2/graph/badge.svg?token=G51NEHYKD3)](https://codecov.io/gh/dotkernel/dot-mail) -[![PHPStan](https://github.com/dotkernel/dot-mail/actions/workflows/static-analysis.yml/badge.svg?branch=5.2)](https://github.com/dotkernel/dot-mail/actions/workflows/static-analysis.yml) +[![Build Static](https://github.com/dotkernel/dot-mail/actions/workflows/continuous-integration.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-mail/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-mail/branch/6.0/graph/badge.svg?token=G51NEHYKD3)](https://codecov.io/gh/dotkernel/dot-mail) +[![PHPStan](https://github.com/dotkernel/dot-mail/actions/workflows/static-analysis.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-mail/actions/workflows/static-analysis.yml) ## Installation @@ -41,152 +42,132 @@ composer require dotkernel/dot-mail ## Configuration +Register `Dot\Mail\ConfigProvider::class` in your configuration aggregator, then copy `config/mail.global.php.dist` into your project's `config/autoload/` directory as `mail.global.php`. + +Mail services are configured under `dot_mail.services`, one block per service. The `default` service is registered by the `ConfigProvider`; register any other one with `Dot\Mail\Factory\MailServiceFactory`. +The factories work with any PSR-11 container that accepts a factory per service key, so Laminas Service Manager users need nothing extra. + ### Mail - Sendmail -If your server has Sendmail installed, update the `config/autoload/mail.local.php.dist` file by setting the `transport` key like below +If your server has Sendmail installed, set the `transport` key like below: ```php [ - 'default' => [ - //... - 'transport' => 'sendmail', - //... - ] - ] -] + 'services' => [ + 'default' => [ + //... + 'transport' => 'sendmail', + //... + ], + ], + ], +]; ``` ### Mail - ESMTP -If you want your application to send mails on e.g., registration, contact, then edit the file `config/autoload/mail.local.php`. -Set the `transport`, `message_options` and `smtp_options` keys like below. +To send through an SMTP server, set the `transport`, `message_options` and `smtp_options` keys like below, preferably in a `config/autoload/mail.local.php` file that is not committed. -Under `message_options` key: +Under the `message_options` key: - `from` - email address from whom users will receive emails -Under `smtp_options` key: +Under the `smtp_options` key: - `host` - the mail server's hostname or IP address - `port` - the mail server's port - `connection_config` - fill in the `username` and `password` keys with the login details of the email used in `from` above -- if you want to disable auto_tls set `tls` key to false - -> Note: all other keys can be left as is. +- to disable TLS, set the `tls` key to `false` ```php [ - 'default' => [ - //... - 'transport' => 'esmtp' - 'message_options' => [ - 'from' => '', + 'services' => [ + 'default' => [ + //... + 'transport' => 'esmtp', + 'message_options' => [ + 'from' => 'sender@example.com', + //... + ], + 'smtp_options' => [ + 'host' => 'smtp.example.com', + 'port' => 587, + 'connection_config' => [ + 'username' => 'sender@example.com', + 'password' => 'secret', + 'tls' => null, + ], + ], //... ], - 'smtp_options' => [ - 'host' => '', - 'port' => 25, - 'connection_config' => [ - 'username' => '', - 'password' => '', - 'tls' => null, - ] - ] - //... - ] - ] -] + ], + ], +]; ``` -In `config/autoload/local.php` add under `contact` => `message_receivers` => `to` key *string* values with the emails that should receive contact messages - -> **Please add at least one email address in order for a contact message to reach someone** - -Also feel free to add as many cc as you want under `contact` => `message_receivers` => `cc` key - ### Sending an e-mail -Below is an example of how to use the email in the most basic way. You can add your own code to it, e.g., to get the user data from a User object or from a config file, to use a template for the body. - -Note that `addTo` is only one of the methods available for the `Message` class returned by `getMessage()`. -Other useful methods that were not included in the example are `addCc()`, `addBcc()`, `addReplyTo()`. - -The returned type is boolean, but if the `isValid()` method is removed, the returned type becomes `MailResult` which allows the use of `getMessage()` for a more detailed error message. -See the `Testing if an e-mail message is valid` section below. - ```php -public function sendBasicMail() +public function sendBasicMail(): void { - $this->mailService->setBody('Email body'); + $this->mailService->setBody('

Email body

'); $this->mailService->setSubject('Email subject'); $this->mailService->getMessage()->addTo('email@example.com', 'User name'); - $this->mailService->getMessage()->setEncoding('utf-8'); - return $this->mailService->send()->isValid(); + $this->mailService->send(); } ``` -It's optional but recommended to call the above function in a `try-catch` block to display helpful error messages. -The next example calls the `sendBasicMail` function from within `UserController`, but you can implement it in other controllers, just make sure that the controller's construct also includes the `FlashMessenger` parameter `$messenger`. +`$this->mailService` is a `Dot\Mail\Service\MailServiceInterface`. +After every `send()` the service restores the configured defaults, so set the recipients, subject and body again for every message. + +`send()` throws `Dot\Mail\Exception\MailException` when the message is invalid or cannot be sent; the original exception is available through `getPrevious()`: ```php +use Dot\Mail\Exception\MailException; + try { $this->userService->sendBasicMail(); $this->messenger->addSuccess('The mail was sent successfully', 'user-login'); - //more code... -} catch (Exception $exception) { - $this->messenger->addError($exception->getMessage(), 'user-login'); - //more code... +} catch (MailException $exception) { + error_log($exception->getPrevious()?->getMessage() ?? $exception->getMessage()); + $this->messenger->addError('The mail could not be sent', 'user-login'); } ``` -### Testing if an e-mail message is valid - -After sending an e-mail, you can check if the message was valid or not. -The `$this->mailService->send()->isValid()` method call will return a boolean value. -If the returned result is `true`, the e-mail was valid, otherwise the e-mail was invalid. -In case your e-mail was invalid, you can check for any errors using `$this->mailService->send()->getMessage()`. - -Using the below logic will let you determine if a message was valid or not and log it. -You can implement your own custom error logging logic. - -```php -$result = $this->mailService->send(); -if (! $result->isValid()) { - //log the error - error_log($result->getMessage()); -} -``` - -> Invalid e-mail messages will not be sent. - ### Logging outgoing emails Optionally, you can keep a log of each successfully sent email. -This might be useful when you need to know if/when a specific email has been sent out to a recipient. - Logs are stored in the following format: ```text -[YYYY-MM-DD HH:MM:SS]: {"subject":"Test subject","to":["Test Account "],"cc":[],"bcc":[]}. +[YYYY-MM-DD HH:MM:SS]: {"subject":"Test subject","to":["Test Account "],"cc":[],"bcc":[]} ``` -To enable it, make sure that your `config/autoload/mail.local.php` has the below `log` configuration under the `dot_mail` key: +To enable it, set the `log` key under `dot_mail`, next to `services`: ```php [ - ... - 'log' => [ - 'sent' => getcwd() . '/log/mail/sent.log' - ] - ] + 'log' => [ + 'sent' => getcwd() . '/log/mail/sent.log', + ], + 'services' => [ + //... + ], + ], ]; ``` To disable it, set the value of `sent` to `null`. + +### Upgrading from 5.x + +See the [upgrade guide](https://docs.dotkernel.org/dot-mail/v6/upgrade-v5-to-v6/). diff --git a/SECURITY.md b/SECURITY.md index d7fa46f..e64f64e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,10 +4,11 @@ | Version | Supported | PHP Version | |---------|-------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| -| 5.2 | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.2%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.2.0) | +| 6.0 | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F6.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/6.0.0) | +| 5.2 | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.2%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.4.0) | | 5.1 | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.1%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.1.0) | | 5.0 | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.0.0) | -| 4.x | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/4.3.0) | +| 4.x | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F4.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/4.3.0) | | <= 3.x | :x: | | ## Reporting Potential Security Issues diff --git a/composer.json b/composer.json index df90d82..09c76a7 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dotkernel/dot-mail", "type": "library", - "description": "Dotkernel mail component based on symfony mailer", + "description": "Dotkernel mail component based on Symfony Mailer, for any PSR-11 container", "license": "MIT", "homepage": "https://github.com/dotkernel/dot-mail", "keywords": [ @@ -10,9 +10,8 @@ "symfony", "mailer", "event", - "dot-event", "laminas", - "laminas-dependency" + "psr-11" ], "authors": [ { @@ -30,17 +29,17 @@ "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "ext-fileinfo": "*", "ext-json": "*", - "dotkernel/dot-event": "^4.0", - "laminas/laminas-servicemanager": "^3.22 || ^4.0", + "laminas/laminas-eventmanager": "^3.4", "laminas/laminas-stdlib": "^3.19", - "symfony/mailer": "^v7.1.6" + "psr/container": "^1.1 || ^2.0", + "symfony/mailer": "^v7.1.6 || ^v8.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", "mikey179/vfsstream": "^v1.6.11", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12" }, "autoload": { "psr-4": { diff --git a/config/mail.global.php.dist b/config/mail.global.php.dist index ad0711d..3d149d8 100644 --- a/config/mail.global.php.dist +++ b/config/mail.global.php.dist @@ -9,78 +9,81 @@ return [ * what you'll usually do, these configs provide just defaults and options that remain the same for all mails */ 'dot_mail' => [ - //the key is the mail service name, this is the default one, which does not extend any configuration - 'default' => [ - //message configuration - 'message_options' => [ - //from email address of the email - 'from' => '', - //from name to be displayed instead of from address - 'from_name' => '', - //reply-to email address of the email - 'reply_to' => '', - //replyTo name to be displayed instead of the address - 'reply_to_name' => '', - //destination email address as string or a list of email addresses - 'to' => [], - //copy destination addresses - 'cc' => [], - //hidden copy destination addresses - 'bcc' => [], - //email subject - 'subject' => '', - //body options - content can be plain text, HTML - 'body' => [ - 'content' => '', - 'charset' => 'utf-8', - ], - //attachments config - 'attachments' => [ - 'files' => [], - 'dir' => [ - 'iterate' => false, - 'path' => 'data/mail/attachments', - 'recursive' => false, + // option to log the SENT emails + 'log' => [ + 'sent' => getcwd() . '/log/mail/sent.log', + ], + //the mail services, indexed by service name + 'services' => [ + //the key is the mail service name, this is the default one + 'default' => [ + //message configuration + 'message_options' => [ + //from email address of the email + 'from' => '', + //from name to be displayed instead of from address + 'from_name' => '', + //reply-to email address of the email + 'reply_to' => '', + //replyTo name to be displayed instead of the address + 'reply_to_name' => '', + //destination email address as string or a list of email addresses + 'to' => [], + //copy destination addresses + 'cc' => [], + //hidden copy destination addresses + 'bcc' => [], + //email subject + 'subject' => '', + //body options - content can be plain text, HTML + 'body' => [ + 'content' => '', + 'charset' => 'utf-8', + ], + //attachments config + 'attachments' => [ + 'files' => [], + 'dir' => [ + 'iterate' => false, + 'path' => 'data/mail/attachments', + 'recursive' => false, + ], ], ], - ], - /** - * the mail transport to use can be any class implementing - * Symfony\Component\Mailer\Transport\TransportInterface - * - * for standard mail transports, you can use these aliases: - * - sendmail => Symfony\Component\Mailer\Transport\SendmailTransport - * - esmtp => Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport - * - * defaults to sendmail - **/ - 'transport' => 'sendmail', - //options that will be used only if esmtp adapter is used - 'smtp_options' => [ - //hostname or IP address of the mail server - 'host' => '', - //port of the mail server - 587 or 465 for secure connections - 'port' => 587, - 'connection_config' => [ - //the smtp authentication identity - 'username' => '', - //the smtp authentication credential - 'password' => '', - /** - * tls will run by default on this component, use: - * - * null - to avoid interfering with automatic encryption - * false - to disable automatic encryption - * - * It's not recommended to disable TLS while connecting to an SMTP server over the Internet - **/ - 'tls' => null, + /** + * the mail transport to use can be any class implementing + * Symfony\Component\Mailer\Transport\TransportInterface + * + * for standard mail transports, you can use these aliases: + * - sendmail => Symfony\Component\Mailer\Transport\SendmailTransport + * - esmtp => Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport + * + * defaults to sendmail + **/ + 'transport' => 'sendmail', + //options that will be used only if esmtp adapter is used + 'smtp_options' => [ + //hostname or IP address of the mail server, required for esmtp + 'host' => '127.0.0.1', + //port of the mail server - 587 or 465 for secure connections + 'port' => 587, + 'connection_config' => [ + //the smtp authentication identity + 'username' => '', + //the smtp authentication credential + 'password' => '', + /** + * tls will run by default on this component, use: + * + * null - to avoid interfering with automatic encryption + * false - to disable automatic encryption + * + * It's not recommended to disable TLS while connecting to an SMTP server over the Internet + **/ + 'tls' => null, + ], ], ], ], - // option to log the SENT emails - 'log' => [ - 'sent' => getcwd() . '/log/mail/sent.log', - ], ], ]; diff --git a/docs/book/v6/configuration.md b/docs/book/v6/configuration.md new file mode 100644 index 0000000..72cc67a --- /dev/null +++ b/docs/book/v6/configuration.md @@ -0,0 +1,163 @@ +# Configuration + +All configuration lives under the `dot_mail` key, usually in `config/autoload/mail.global.php`, copied from `config/mail.global.php.dist`. + +```php +return [ + 'dot_mail' => [ + 'log' => [ + 'sent' => getcwd() . '/log/mail/sent.log', + ], + 'services' => [ + 'default' => [ + 'message_options' => [/* ... */], + 'transport' => 'sendmail', + 'smtp_options' => [/* ... */], + 'event_listeners' => [], + ], + ], + ], +]; +``` + +- `dot_mail.services` holds one block per mail service, indexed by the service name. +- `dot_mail.log` is shared by all services and stays outside `services`. + +> A configuration in the 5.x layout, with services directly under `dot_mail`, fails with an `InvalidArgumentException`. +> See [Upgrading from v5 to v6](upgrade-v5-to-v6.md). + +## Mail services + +The `default` service is registered by `Dot\Mail\ConfigProvider` as `dot-mail.service.default`, and `Dot\Mail\Service\MailServiceInterface` is an alias of it. + +To use another service, add its block under `dot_mail.services` and register it in your dependencies with `Dot\Mail\Factory\MailServiceFactory`: + +```php +return [ + 'dependencies' => [ + 'factories' => [ + 'dot-mail.service.newsletter' => \Dot\Mail\Factory\MailServiceFactory::class, + ], + ], + 'dot_mail' => [ + 'services' => [ + 'default' => [/* ... */], + 'newsletter' => [/* ... */], + ], + ], +]; +``` + +The options of a service are available as `dot-mail.options.` when registered with `Dot\Mail\Factory\MailOptionsFactory`; `dot-mail.options.default` is registered by the `ConfigProvider`. + +## Message options + +`message_options` holds the defaults of every message sent by the service: + +| Key | Type | Description | +| --- | --- | --- | +| `from`, `from_name` | string | Sender address and display name | +| `reply_to`, `reply_to_name` | string | Reply-to address and display name | +| `to`, `cc`, `bcc` | list of strings | Default recipients | +| `subject` | string | Default subject | +| `body.content` | string | Default HTML body; an empty string sets no body | +| `body.charset` | string | Charset of the default body, `utf-8` by default | +| `attachments.files` | list of paths | Files attached to every message | +| `attachments.dir` | array | Directory scanned for attachments, see below | + +Each value can be changed for a single message through the mail service, see [Usage](usage.md): + +```php +// replaces the configured recipients +$mailService->getMessage()->setTo('receiver@example.com'); + +// keeps the configured recipients and adds one +$mailService->getMessage()->addTo('receiver@example.com'); +``` + +The service restores these defaults after every `send()`. + +### Attachments directory + +```php +'attachments' => [ + 'files' => [], + 'dir' => [ + 'iterate' => true, + 'path' => 'data/mail/attachments', + 'recursive' => false, + ], +], +``` + +When `iterate` is `true`, every file in `path` is attached; with `recursive`, files in subdirectories too. +The directory is read at send time, so files added later are included. +Files and directories whose name starts with a dot are skipped. +A relative `path` is resolved against the current working directory. + +## Transport + +`transport` selects how messages are delivered. It can be: + +- `sendmail` (the default when the key is omitted) or `esmtp`, case-insensitive +- the name of a class implementing `Symfony\Component\Mailer\Transport\TransportInterface`, created without arguments +- the name of a container service that returns a `TransportInterface` +- a `TransportInterface` object, used as given + +See [Transports](transports.md). + +### SMTP options + +`smtp_options` is used only by the `esmtp` transport: + +```php +'smtp_options' => [ + 'host' => 'smtp.example.com', + 'port' => 587, + 'name' => 'client.example.com', + 'connection_time_limit' => 30, + 'connection_config' => [ + 'username' => 'user@example.com', + 'password' => 'secret', + 'tls' => null, + ], +], +``` + +| Key | Default | Description | +| --- | --- | --- | +| `host` | `127.0.0.1` | Hostname or IP address of the mail server; set it for any real server | +| `port` | `25` | `587` for submission with STARTTLS, `465` for implicit TLS | +| `name` | transport default | Local client name sent in the `EHLO` greeting | +| `connection_time_limit` | transport default | Socket timeout in seconds | +| `connection_config.username`, `password` | none | Credentials; empty values send no authentication; special characters need no encoding | +| `connection_config.tls` | `null` | `null` lets the transport choose (STARTTLS when offered, implicit TLS on port 465); `false` disables TLS | + +> It's not recommended to disable TLS while connecting to an SMTP server over the Internet. + +## Event listeners + +`event_listeners` lists the container services that receive the mail events, either as a service name or with a priority: + +```php +'event_listeners' => [ + \App\Mail\AuditListener::class, + ['type' => \App\Mail\MetricsListener::class, 'priority' => 10], +], +``` + +Each service must implement `Dot\Mail\Event\MailEventListenerInterface`; see [Usage](usage.md#events). +An entry of any other shape fails with a `Dot\Mail\Exception\RuntimeException`. + +## Logging + +```php +'dot_mail' => [ + 'log' => [ + 'sent' => getcwd() . '/log/mail/sent.log', + ], +], +``` + +`log.sent` is the file that receives one line per sent email; missing directories are created. +Set it to `null` to disable logging. diff --git a/docs/book/v6/installation.md b/docs/book/v6/installation.md new file mode 100644 index 0000000..6c04881 --- /dev/null +++ b/docs/book/v6/installation.md @@ -0,0 +1,25 @@ +# Installation + +`dot-mail` 6 requires PHP 8.3 or newer. + +Install `dotkernel/dot-mail` by executing the following Composer command: + +```shell +composer require dotkernel/dot-mail +``` + +Register the package by adding `Dot\Mail\ConfigProvider::class` to your configuration aggregator, for example in `config/config.php`: + +```php +$aggregator = new ConfigAggregator([ + // ... + \Dot\Mail\ConfigProvider::class, + // ... +]); +``` + +Then copy `vendor/dotkernel/dot-mail/config/mail.global.php.dist` into your project's `config/autoload/` directory as `mail.global.php`, and fill it in as described in [Configuration](configuration.md). +Keep credentials, such as the SMTP password, in a `mail.local.php` file that is not committed. + +The factories only use `Psr\Container\ContainerInterface`, so they work with any PSR-11 container that accepts a factory per service key. +Applications that use Laminas Service Manager, such as Mezzio applications, need nothing extra. diff --git a/docs/book/v6/overview.md b/docs/book/v6/overview.md new file mode 100644 index 0000000..915999d --- /dev/null +++ b/docs/book/v6/overview.md @@ -0,0 +1,43 @@ +# Overview + +Dotkernel's mail service. + +> dot-mail is a wrapper on top of [symfony mailer](https://github.com/symfony/mailer) + +## Requirements + +- PHP 8.3, 8.4, 8.5 or 8.6 +- `symfony/mailer` 7.1.6 or newer, or 8.x +- any [PSR-11](https://www.php-fig.org/psr/psr-11/) container that accepts a factory per service key, for example `laminas/laminas-servicemanager` + +## Version History + +| Branch | Release | PSR-11 | Mailer | OSS Lifecycle | PHP Version | +|--------|------------------|----------|------------------|-------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| +| 6.0 | `>=6.0.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F6.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/6.0.0) | +| 5.2 | `>=5.2.0 <6.0.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.2%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.4.0) | +| 5.1 | `<5.2.0` | 1 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.1%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.1.6) | +| 5.0 | `<5.1.0` | 1 \|\| 2 | `symfony/mailer` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F5.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/5.0.4) | +| 4.0 | `<=4.3.0` | 1 | `laminas-mail` | ![OSS Lifecycle](https://img.shields.io/osslifecycle?file_url=https%3A%2F%2Fgithub.com%2Fdotkernel%2Fdot-mail%2Fblob%2F4.0%2FOSSMETADATA) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/4.3.0) | + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-mail) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-mail/6.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-mail)](https://github.com/dotkernel/dot-mail/blob/6.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-mail/actions/workflows/continuous-integration.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-mail/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-mail/branch/6.0/graph/badge.svg?token=G51NEHYKD3)](https://codecov.io/gh/dotkernel/dot-mail) +[![PHPStan](https://github.com/dotkernel/dot-mail/actions/workflows/static-analysis.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-mail/actions/workflows/static-analysis.yml) + +## Features + +- Several mail services in one application, each with its own defaults, transport and listeners. +- Transports: `sendmail`, `esmtp`, any class implementing `Symfony\Component\Mailer\Transport\TransportInterface`, or a transport service from the container. +- Attachments from file paths or from a directory scanned at send time. +- Events before sending, after sending and on errors. +- An optional log of every sent email. diff --git a/docs/book/v6/transports.md b/docs/book/v6/transports.md new file mode 100644 index 0000000..1226a81 --- /dev/null +++ b/docs/book/v6/transports.md @@ -0,0 +1,44 @@ +# Transports + +`dot-mail` sends through any class implementing `Symfony\Component\Mailer\Transport\TransportInterface`. +The `transport` key of a mail service accepts: + +| Value | Result | +| --- | --- | +| `sendmail` (default) | `Symfony\Component\Mailer\Transport\SendmailTransport` | +| `esmtp` | `Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport`, built from `smtp_options` | +| A container service name | The service, which must return a `TransportInterface` | +| A class name | A new instance of the class, created without constructor arguments | +| A `TransportInterface` object | The object, used as given | + +## sendmail + +`sendmail` hands messages to the local sendmail binary. +It needs a working mail transfer agent on the server, and messages sent this way are more often classified as spam. + +## esmtp + +`esmtp` connects to the SMTP server configured in `smtp_options`; see [Configuration](configuration.md#smtp-options). + +## Custom transports + +Any other Symfony transport, for example one from a `symfony/*-mailer` bridge, can be registered as a container service and referenced by name: + +```php +return [ + 'dependencies' => [ + 'factories' => [ + 'mail.transport.api' => \App\Mail\ApiTransportFactory::class, + ], + ], + 'dot_mail' => [ + 'services' => [ + 'default' => [ + 'transport' => 'mail.transport.api', + ], + ], + ], +]; +``` + +The service can also be replaced for a single mail service at runtime with `setTransport()`. diff --git a/docs/book/v6/upgrade-v5-to-v6.md b/docs/book/v6/upgrade-v5-to-v6.md new file mode 100644 index 0000000..d741c59 --- /dev/null +++ b/docs/book/v6/upgrade-v5-to-v6.md @@ -0,0 +1,119 @@ +# Upgrading from v5 to v6 + +Version 6 requires PHP 8.3 or newer. +In your `composer.json`, require `"dotkernel/dot-mail": "^6.0"` and run `composer update dotkernel/dot-mail`. + +Then go through the sections below. The [table of breaking changes](#breaking-changes) lists every change that can affect your code. + +## Moving the services under `services` + +Mail services are now configured under `dot_mail.services`. The `log` key stays where it is. + +Before: + +```php +return [ + 'dot_mail' => [ + 'default' => [ + 'message_options' => [/* ... */], + 'transport' => 'esmtp', + 'smtp_options' => [/* ... */], + ], + 'log' => [ + 'sent' => getcwd() . '/log/mail/sent.log', + ], + ], +]; +``` + +After: + +```php +return [ + 'dot_mail' => [ + 'services' => [ + 'default' => [ + 'message_options' => [/* ... */], + 'transport' => 'esmtp', + 'smtp_options' => [/* ... */], + ], + ], + 'log' => [ + 'sent' => getcwd() . '/log/mail/sent.log', + ], + ], +]; +``` + +A configuration in the old layout fails with: `Mail service "default" must be configured under "dot_mail.services"`. +Compare with the new `config/mail.global.php.dist`. + +## Replacing the abstract factories + +`Dot\Mail\Factory\AbstractMailFactory`, `MailServiceAbstractFactory` and `MailOptionsAbstractFactory` were removed, together with the `abstract_factories` entry of the `ConfigProvider`. +The new `MailServiceFactory` and `MailOptionsFactory` are plain PSR-11 factories, so `dot-mail` no longer requires `laminas/laminas-servicemanager`. + +The `ConfigProvider` registers `dot-mail.service.default` and `dot-mail.options.default`. If you only use the default service, there is nothing to change. + +Every other mail service has to be registered. Before, the abstract factory resolved any `dot-mail.service.` configured under `dot_mail`: + +```php +$newsletter = $container->get('dot-mail.service.newsletter'); +``` + +After, register the key with the factory, then get it as before: + +```php +return [ + 'dependencies' => [ + 'factories' => [ + 'dot-mail.service.newsletter' => \Dot\Mail\Factory\MailServiceFactory::class, + // only if you get the options themselves from the container: + 'dot-mail.options.newsletter' => \Dot\Mail\Factory\MailOptionsFactory::class, + ], + ], +]; +``` + +If your own code listed one of the removed classes, for example in an `abstract_factories` configuration, remove that entry. + +## Sending + +Set the recipients, subject, body and attachments before every `send()`: the service restores the configured defaults after each attempt. + +`send()` never returns an invalid result. Replace checks of `isValid()` with a `try`/`catch`: + +```php +use Dot\Mail\Exception\MailException; + +try { + $this->mailService->send(); +} catch (MailException $exception) { + error_log($exception->getPrevious()?->getMessage() ?? $exception->getMessage()); +} +``` + +## Breaking changes + +| Change | Symptom | Fix | +| --- | --- | --- | +| Services under `dot_mail.services` | `InvalidArgumentException`: `Mail service "default" must be configured under "dot_mail.services"` | Move each service block under `services`; keep `log` where it is | +| Abstract factories removed | Service not found for `dot-mail.service.` other than `default`; class not found for `MailServiceAbstractFactory` | Register `'dot-mail.service.' => MailServiceFactory::class` | +| `send()` resets after each attempt | A second email has no recipients, subject or body | Set them before every `send()` | +| `send()` throws instead of returning an invalid result | `isValid()` checks are never `false` | Catch `MailException` | +| `send()` handles `Throwable`; `ResultInterface`, `MailResult` and `createMailResultFromException()` use `Throwable` | Your implementation of `ResultInterface` fails to load | Change `Exception` to `Throwable` in it | +| Post-send listener exceptions propagate | An exception reaches the caller after the email was sent | Catch it in the listener or around `send()` | +| A missing attachment throws | `MailException` instead of a silently skipped file | Check paths before `addAttachment()` | +| Attachment directory read at send time; dotfiles and dot-directories skipped | Different attachments than before | Move files the email needs out of hidden directories | +| `sendmail` is the default transport | Mail goes through sendmail when `transport` is omitted | Set `transport` explicitly | +| `esmtp` built from `smtp_options` instead of a DSN | `smtp_options.name` and `connection_time_limit` now take effect | Check these values | +| A transport object or service is used as given | Your transport is no longer replaced | Remove workarounds | +| An empty body fails validation; empty `body.content` is not applied | `MailException`: `A message must have a text or an HTML part.` | Set a body | +| `setBody()` charset and `body.charset` are used | A different `Content-Type` charset | Pass the charset you need | +| `MailEvent::getResult()` returns `?ResultInterface` | Null access in a pre-send listener | Check for `null` | +| `MailServiceInterface::setBody()` accepts `string\|AbstractPart` | Fatal error in your implementation of the interface | Widen the parameter | +| `MailEvent` extends `Laminas\EventManager\Event` instead of `Dot\Event\Event` | `instanceof Dot\Event\Event` is `false` | Check against `MailEvent` or `Laminas\EventManager\EventInterface` | +| `Email::setSender()` parameter renamed from `$addresses` to `$address` | A named argument `addresses:` fails | Use `address:` or a positional argument | +| `SmtpOptions::getName()` returns `?string`, `null` by default | Type error in code expecting `string` | Handle `null` | +| An unconfigured mail service throws | `InvalidArgumentException`: `Mail service "" is not configured under "dot_mail.services"` | Configure the service | +| PHP 8.3 minimum | Composer refuses to install | Upgrade PHP | diff --git a/docs/book/v6/usage.md b/docs/book/v6/usage.md new file mode 100644 index 0000000..0bae3f6 --- /dev/null +++ b/docs/book/v6/usage.md @@ -0,0 +1,137 @@ +# Usage + +## Getting the mail service + +Inject `Dot\Mail\Service\MailServiceInterface` to use the `default` mail service: + +```php +use Dot\Mail\Service\MailServiceInterface; + +class UserService +{ + public function __construct( + private MailServiceInterface $mailService, + ) { + } +} +``` + +For another configured service, get `dot-mail.service.` from the container, for example `dot-mail.service.newsletter`. +See [Configuration](configuration.md#mail-services) for how to register it. + +## Sending an e-mail + +```php +public function sendBasicMail(): void +{ + $this->mailService->setBody('

Email body

'); + $this->mailService->setSubject('Email subject'); + $this->mailService->getMessage()->addTo('email@example.com', 'User name'); + $this->mailService->send(); +} +``` + +`getMessage()` returns a `Dot\Mail\Email`, which also has `addCc()`, `addBcc()`, `addReplyTo()`, `setFrom()`, `setSender()` and `priority()`. +The address methods accept a string, a `Symfony\Component\Mime\Address`, or an array of either. + +`send()` returns a valid `Dot\Mail\Result\ResultInterface` when the message was handed to the transport. +When the message is invalid (for example without recipients or without a body) or the transport fails, `send()` throws `Dot\Mail\Exception\MailException`. +The original exception is available through `getPrevious()`: + +```php +use Dot\Mail\Exception\MailException; + +try { + $this->userService->sendBasicMail(); + $this->messenger->addSuccess('The mail was sent successfully', 'user-login'); +} catch (MailException $exception) { + error_log($exception->getPrevious()?->getMessage() ?? $exception->getMessage()); + $this->messenger->addError('The mail could not be sent', 'user-login'); +} +``` + +### Every send starts from the configured defaults + +After every `send()`, successful or not, the service restores the message and the attachments configured in `message_options`. +Set the recipients, subject, body and attachments again for every message. +`getMessage()` returns a new object after each send, so do not keep a reference to it. + +`reset()` restores the defaults without sending. + +## Body + +```php +// HTML body in utf-8 +$this->mailService->setBody('

Hello

'); + +// HTML body in another charset +$this->mailService->setBody('

Hello

', 'iso-8859-1'); + +// any MIME part, used as given; the charset argument is ignored +$this->mailService->setBody(new \Symfony\Component\Mime\Part\TextPart('Plain text body')); +``` + +A plain-text alternative can be added with `getMessage()->text('Plain text version')`. +A message without any body fails validation. + +## Attachments + +```php +$this->mailService->addAttachment('/path/to/invoice.pdf'); + +// attached as "ticket.pdf" +$this->mailService->addAttachment('/path/to/file-123.pdf', 'ticket.pdf'); + +$this->mailService->addAttachments(['/path/to/a.txt', '/path/to/b.txt']); +``` + +Attachments configured in `message_options.attachments` are added to every message. +A file that does not exist or cannot be read makes `send()` throw a `MailException`. + +## Events + +Listeners extend `Dot\Mail\Event\AbstractMailEventListener` and override the events they need: + +```php +use Dot\Mail\Event\AbstractMailEventListener; +use Dot\Mail\Event\MailEvent; + +class AuditListener extends AbstractMailEventListener +{ + public function onPreSend(MailEvent $e): void + { + $e->getMailService()->getMessage()->addBcc('audit@example.com'); + } + + public function onPostSend(MailEvent $e): void + { + // the message was delivered to the transport + } + + public function onSendError(MailEvent $e): void + { + error_log((string) $e->getResult()?->getMessage()); + } +} +``` + +- `onPreSend` runs before the attachments are added and the message is sent. `getResult()` returns `null`. +- `onPostSend` runs after a successful send, before the message is reset. An exception thrown here reaches the caller of `send()` unchanged: the message was already delivered. +- `onSendError` runs when sending fails. `getResult()->getException()` returns the original exception. + +Register listeners in the `event_listeners` configuration key, or call `attachListener()` on the service. +`MailEvent` extends `Laminas\EventManager\Event`. + +## Logging outgoing emails + +When `dot_mail.log.sent` is set, `Dot\Mail\Service\LogService` appends one line per sent email to that file: + +```text +[YYYY-MM-DD HH:MM:SS]: {"subject":"Test subject","to":["Test Account "],"cc":[],"bcc":[]} +``` + +A failure to write the log does not turn a delivered email into an error. + +## Transport usage + +See [Transports](transports.md). diff --git a/mkdocs.yml b/mkdocs.yml index 0f63cdc..f72143f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,12 +2,20 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v5 + current_version: v6 versions: + - v6 - v5 - v4 nav: - Home: index.md + - v6: + - Overview: v6/overview.md + - Installation: v6/installation.md + - Configuration: v6/configuration.md + - Usage: v6/usage.md + - Transports: v6/transports.md + - Upgrade from v5 to v6: v6/upgrade-v5-to-v6.md - v5: - Overview: v5/overview.md - Installation: v5/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index dfd062d..52e8777 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,15 +1,22 @@ + colors="true" + displayDetailsOnAllIssues="true" + failOnDeprecation="true" + failOnNotice="true" + failOnPhpunitDeprecation="true" + failOnPhpunitNotice="true" + failOnRisky="true" + failOnWarning="true"> ./test - + ./src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 6f6ae8e..0cd9964 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -5,13 +5,23 @@ namespace Dot\Mail; use Dot\Mail\Factory\LogServiceFactory; -use Dot\Mail\Factory\MailOptionsAbstractFactory; -use Dot\Mail\Factory\MailServiceAbstractFactory; +use Dot\Mail\Factory\MailOptionsFactory; +use Dot\Mail\Factory\MailServiceFactory; use Dot\Mail\Service\LogService; use Dot\Mail\Service\LogServiceInterface; +use Dot\Mail\Service\MailServiceInterface; +/** + * @phpstan-type DependencyConfig array{ + * factories: array>, + * aliases: array + * } + */ class ConfigProvider { + /** + * @return array{dependencies: DependencyConfig} + */ public function __invoke(): array { return [ @@ -19,18 +29,23 @@ public function __invoke(): array ]; } + /** + * Registers the default mail service. Register other mail services the same way, for example + * 'dot-mail.service.newsletter' => MailServiceFactory::class + * + * @return DependencyConfig + */ public function getDependencyConfig(): array { return [ - 'factories' => [ - LogService::class => LogServiceFactory::class, + 'factories' => [ + LogService::class => LogServiceFactory::class, + 'dot-mail.service.default' => MailServiceFactory::class, + 'dot-mail.options.default' => MailOptionsFactory::class, ], - 'aliases' => [ - LogServiceInterface::class => LogService::class, - ], - 'abstract_factories' => [ - MailServiceAbstractFactory::class, - MailOptionsAbstractFactory::class, + 'aliases' => [ + LogServiceInterface::class => LogService::class, + MailServiceInterface::class => 'dot-mail.service.default', ], ]; } diff --git a/src/Email.php b/src/Email.php index 7640ce7..54a71b2 100644 --- a/src/Email.php +++ b/src/Email.php @@ -12,20 +12,12 @@ use Symfony\Component\Mime\Message; use Symfony\Component\Mime\Part\AbstractPart; use Symfony\Component\Mime\Part\Multipart\AlternativePart; -use Symfony\Component\Mime\Part\Multipart\MixedPart; -use Symfony\Component\Mime\Part\Multipart\RelatedPart; use Symfony\Component\Mime\Part\TextPart; -use function array_filter; -use function array_merge; -use function array_unique; -use function array_values; use function is_array; use function is_string; -use function preg_match_all; +use function preg_match; use function sprintf; -use function sscanf; -use function str_replace; class Email extends Message { @@ -48,7 +40,6 @@ class Email extends Message private ?string $html = null; private ?string $htmlCharset = null; - private array $attachments = []; public function subject(string $subject): static { @@ -80,9 +71,11 @@ public function getReturnPath(): ?Address return $this->getHeaders()->getHeaderBody('Return-Path'); } - public function setSender(Address|string $addresses, mixed $name = null): static + public function setSender(Address|string $address, ?string $name = null): static { - return $this->setHeaderBody('Mailbox', 'Sender', new Address($addresses, $name ?? '')); + $sender = $address instanceof Address ? $address : new Address($address, $name ?? ''); + + return $this->setHeaderBody('Mailbox', 'Sender', $sender); } public function getSender(): ?Address @@ -90,40 +83,61 @@ public function getSender(): ?Address return $this->getHeaders()->getHeaderBody('Sender'); } + /** + * @param array|Address|string $addresses + */ public function addFrom(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->addListAddressHeaderBody('From', $updatedAddresses); } + /** + * @param array|Address|string $addresses + */ public function setFrom(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->setListAddressHeaderBody('From', $updatedAddresses); } + /** + * @return Address[] + */ public function getFrom(): array { return $this->getHeaders()->getHeaderBody('From') ?: []; } + /** + * @param array|Address|string $addresses + */ public function addReplyTo(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->addListAddressHeaderBody('Reply-To', $updatedAddresses); } + /** + * @param array|Address|string $addresses + */ public function setReplyTo(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->setListAddressHeaderBody('Reply-To', $updatedAddresses); } + /** + * @return Address[] + */ public function getReplyTo(): array { return $this->getHeaders()->getHeaderBody('Reply-To') ?: []; } + /** + * @param array|Address|string $addresses + */ public function addTo(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); @@ -132,46 +146,70 @@ public function addTo(array|Address|string $addresses, ?string $name = null): st return $this; } + /** + * @param array|Address|string $addresses + */ public function setTo(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->setListAddressHeaderBody('To', $updatedAddresses); } + /** + * @return Address[] + */ public function getTo(): array { return $this->getHeaders()->getHeaderBody('To') ?: []; } + /** + * @param array|Address|string $addresses + */ public function addCc(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->addListAddressHeaderBody('Cc', $updatedAddresses); } + /** + * @param array|Address|string $addresses + */ public function setCc(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->setListAddressHeaderBody('Cc', $updatedAddresses); } + /** + * @return Address[] + */ public function getCc(): array { return $this->getHeaders()->getHeaderBody('Cc') ?: []; } + /** + * @param array|Address|string $addresses + */ public function addBcc(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->addListAddressHeaderBody('Bcc', $updatedAddresses); } + /** + * @param array|Address|string $addresses + */ public function setBcc(array|Address|string $addresses, ?string $name = null): static { $updatedAddresses = $this->updateAddresses($addresses, $name ?? ''); return $this->setListAddressHeaderBody('Bcc', $updatedAddresses); } + /** + * @return Address[] + */ public function getBcc(): array { return $this->getHeaders()->getHeaderBody('Bcc') ?: []; @@ -190,9 +228,9 @@ public function priority(int $priority): static public function getPriority(): int { - [$priority] = sscanf($this->getHeaders()->getHeaderBody('X-Priority') ?? '', '%[1-5]'); + $header = (string) $this->getHeaders()->getHeaderBody('X-Priority'); - return $priority !== null ? (int) $priority : 3; + return preg_match('/^([1-5])/', $header, $matches) === 1 ? (int) $matches[1] : self::PRIORITY_NORMAL; } public function text(string $body, string $charset = 'utf-8'): static @@ -265,8 +303,8 @@ public function ensureValidity(): void private function ensureBodyValid(): void { - if (null === $this->text && null === $this->html && ! $this->attachments) { - throw new LogicException('A message must have a text or an HTML part or attachments.'); + if (null === $this->text && null === $this->html && null === parent::getBody()) { + throw new LogicException('A message must have a text or an HTML part.'); } } @@ -274,81 +312,15 @@ private function generateBody(): AbstractPart { $this->ensureBodyValid(); - [$htmlPart, $otherParts, $relatedParts] = $this->prepareParts(); - $part = null === $this->text ? null : new TextPart($this->text, $this->textCharset); - if (null !== $htmlPart) { - if (null !== $part) { - $part = new AlternativePart($part, $htmlPart); - } else { - $part = $htmlPart; - } - } - - if ($relatedParts) { - $part = new RelatedPart($part, ...$relatedParts); - } - - if ($otherParts) { - if ($part) { - $part = new MixedPart($part, ...$otherParts); - } else { - $part = new MixedPart(...$otherParts); - } + if (null !== $this->html) { + $htmlPart = new TextPart($this->html, $this->htmlCharset, 'html'); + $part = null !== $part ? new AlternativePart($part, $htmlPart) : $htmlPart; } return $part ?? new TextPart((string) $this->text, $this->textCharset); } - private function prepareParts(): array - { - $names = []; - $htmlPart = null; - $html = $this->html; - if (null !== $html) { - $htmlPart = new TextPart($html, $this->htmlCharset, 'html'); - $html = $htmlPart->getBody(); - - $regexes = [ - ']*src\s*=\s*(?:([\'"])cid:(.+?)\\1|cid:([^>\s]+))', - '<\w+\s+[^>]*background\s*=\s*(?:([\'"])cid:(.+?)\\1|cid:([^>\s]+))', - ]; - $tmpMatches = []; - foreach ($regexes as $regex) { - preg_match_all('/' . $regex . '/i', $html, $tmpMatches); - $names = array_merge($names, $tmpMatches[2], $tmpMatches[3]); - } - $names = array_filter(array_unique($names)); - } - - $otherParts = $relatedParts = []; - foreach ($this->attachments as $part) { - foreach ($names as $name) { - if ($name !== $part->getName() && (! $part->hasContentId() || $name !== $part->getContentId())) { - continue; - } - if (isset($relatedParts[$name])) { - continue 2; - } - - if ($name !== $part->getContentId()) { - $html = str_replace('cid:' . $name, 'cid:' . $part->getContentId(), $html, $count); - } - $relatedParts[$name] = $part; - $part->setName($part->getContentId())->asInline(); - - continue 2; - } - - $otherParts[] = $part; - } - if (null !== $htmlPart) { - $htmlPart = new TextPart($html, $this->htmlCharset, 'html'); - } - - return [$htmlPart, $otherParts, array_values($relatedParts)]; - } - private function setHeaderBody(string $type, string $name, mixed $body): static { $this->getHeaders()->setHeaderBody($type, $name, $body); @@ -356,6 +328,9 @@ private function setHeaderBody(string $type, string $name, mixed $body): static return $this; } + /** + * @param Address[] $addresses + */ private function addListAddressHeaderBody(string $name, array $addresses): static { $header = $this->getHeaders()->get($name); @@ -367,6 +342,9 @@ private function addListAddressHeaderBody(string $name, array $addresses): stati return $this; } + /** + * @param Address[] $addresses + */ private function setListAddressHeaderBody(string $name, array $addresses): static { $addresses = Address::createArray($addresses); @@ -380,6 +358,10 @@ private function setListAddressHeaderBody(string $name, array $addresses): stati return $this; } + /** + * @param array|Address|string $addresses + * @return Address[] + */ private function updateAddresses(array|Address|string $addresses, ?string $name = null): array { if (is_array($addresses)) { @@ -394,6 +376,10 @@ private function updateAddresses(array|Address|string $addresses, ?string $name return [$addresses]; } + /** + * @param array $addresses + * @return Address[] + */ private function createAddresses(array $addresses, ?string $name = null): array { $createdAddresses = []; diff --git a/src/Event/MailEvent.php b/src/Event/MailEvent.php index 5ad801f..42f4610 100644 --- a/src/Event/MailEvent.php +++ b/src/Event/MailEvent.php @@ -4,15 +4,12 @@ namespace Dot\Mail\Event; -use ArrayAccess; -use Dot\Event\Event; use Dot\Mail\Result\ResultInterface; use Dot\Mail\Service\MailServiceInterface; +use Laminas\EventManager\Event; /** - * @template TTarget of object|string|null - * @template TParams of array|ArrayAccess|object - * @extends Event + * @extends Event> */ class MailEvent extends Event { @@ -21,7 +18,7 @@ class MailEvent extends Event public const EVENT_MAIL_SEND_ERROR = 'event.mail.send.error'; protected MailServiceInterface $mailService; - protected ResultInterface $result; + protected ?ResultInterface $result = null; public function __construct(MailServiceInterface $mailService, string $name = self::EVENT_MAIL_PRE_SEND) { @@ -39,7 +36,7 @@ public function setMailService(MailServiceInterface $mailService): void $this->mailService = $mailService; } - public function getResult(): ResultInterface + public function getResult(): ?ResultInterface { return $this->result; } diff --git a/src/Event/MailEventListenerAwareTrait.php b/src/Event/MailEventListenerAwareTrait.php index cefa815..a189f69 100644 --- a/src/Event/MailEventListenerAwareTrait.php +++ b/src/Event/MailEventListenerAwareTrait.php @@ -12,6 +12,7 @@ trait MailEventListenerAwareTrait { use EventManagerAwareTrait; + /** @var MailEventListenerInterface[] */ protected array $listeners = []; public function attachListener(MailEventListenerInterface $listener, int $priority = 1): void diff --git a/src/Factory/AbstractMailFactory.php b/src/Factory/AbstractMailFactory.php deleted file mode 100644 index 6ada22a..0000000 --- a/src/Factory/AbstractMailFactory.php +++ /dev/null @@ -1,56 +0,0 @@ -getConfig($container); - return array_key_exists($specificServiceName, $config); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function getConfig(ContainerInterface $container): array - { - $config = $container->get('config'); - if (isset($config[$this->configKey]) && is_array($config[$this->configKey])) { - $this->config = $config[$this->configKey]; - } - - return $this->config; - } -} diff --git a/src/Factory/MailConfig.php b/src/Factory/MailConfig.php new file mode 100644 index 0000000..a30b1f7 --- /dev/null +++ b/src/Factory/MailConfig.php @@ -0,0 +1,103 @@ +.`. + */ + public static function serviceName(string $requestedName, string $part): string + { + $parts = explode('.', $requestedName); + if (count($parts) !== 3 || $parts[0] !== self::DOT_MAIL_PART || $parts[1] !== $part || $parts[2] === '') { + throw new InvalidArgumentException(sprintf( + 'Mail service key must have the form "%s.%s."; "%s" given', + self::DOT_MAIL_PART, + $part, + $requestedName + )); + } + + return $parts[2]; + } + + /** + * Returns the configured mail services, indexed by name (the `dot_mail.services` key). + * + * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws InvalidArgumentException When the configuration uses the pre-6.0 layout. + */ + public static function services(ContainerInterface $container): array + { + $config = $container->has('config') ? $container->get('config') : []; + if (! is_array($config) || ! isset($config[self::CONFIG_KEY]) || ! is_array($config[self::CONFIG_KEY])) { + return []; + } + + $mailConfig = $config[self::CONFIG_KEY]; + if (isset($mailConfig[self::SERVICES_KEY]) && is_array($mailConfig[self::SERVICES_KEY])) { + return $mailConfig[self::SERVICES_KEY]; + } + + foreach ($mailConfig as $key => $value) { + if ($key !== self::LOG_KEY && is_array($value)) { + throw new InvalidArgumentException(sprintf( + 'Mail service "%s" must be configured under "%s.%s"; see the upgrade guide to version 6', + $key, + self::CONFIG_KEY, + self::SERVICES_KEY + )); + } + } + + return []; + } + + /** + * Returns the configuration of one mail service. + * + * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws InvalidArgumentException When the service is not configured under `dot_mail.services`. + */ + public static function service(ContainerInterface $container, string $name): array + { + $services = self::services($container); + if (! isset($services[$name]) || ! is_array($services[$name])) { + throw new InvalidArgumentException(sprintf( + 'Mail service "%s" is not configured under "%s.%s"', + $name, + self::CONFIG_KEY, + self::SERVICES_KEY + )); + } + + return $services[$name]; + } +} diff --git a/src/Factory/MailOptionsAbstractFactory.php b/src/Factory/MailOptionsAbstractFactory.php deleted file mode 100644 index 0d1fb56..0000000 --- a/src/Factory/MailOptionsAbstractFactory.php +++ /dev/null @@ -1,36 +0,0 @@ -getConfig($container); - $specificConfig = $config[$specificServiceName]; - if (! is_array($specificConfig)) { - $specificConfig = []; - } - - return new MailOptions($specificConfig); - } -} diff --git a/src/Factory/MailOptionsFactory.php b/src/Factory/MailOptionsFactory.php new file mode 100644 index 0000000..b0df8a4 --- /dev/null +++ b/src/Factory/MailOptionsFactory.php @@ -0,0 +1,34 @@ +`. + * Works with any PSR-11 container that accepts a factory per service key. + */ +class MailOptionsFactory +{ + public const SPECIFIC_PART = 'options'; + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws InvalidArgumentException When the service is not configured under dot_mail.services. + */ + public function __invoke( + ContainerInterface $container, + string $requestedName = MailConfig::DOT_MAIL_PART . '.' . self::SPECIFIC_PART . '.default' + ): MailOptions { + $name = MailConfig::serviceName($requestedName, self::SPECIFIC_PART); + + return new MailOptions(MailConfig::service($container, $name)); + } +} diff --git a/src/Factory/MailServiceAbstractFactory.php b/src/Factory/MailServiceAbstractFactory.php deleted file mode 100644 index d104550..0000000 --- a/src/Factory/MailServiceAbstractFactory.php +++ /dev/null @@ -1,242 +0,0 @@ -mailOptions = $container->get( - sprintf( - '%s.%s.%s', - self::DOT_MAIL_PART, - MailOptionsAbstractFactory::SPECIFIC_PART, - $specificServiceName - ) - ); - - $logService = $container->get(LogServiceInterface::class); - $message = $this->createMessage(); - $transport = $this->createTransport($container); - - $mailService = new MailService($logService, $message, $transport, $this->mailOptions); - - //set subject - $mailService->setSubject($this->mailOptions->getMessageOptions()->getSubject()); - - $body = $this->mailOptions->getMessageOptions()->getBody(); - - $mailService->setBody($body->getContent(), $body->getCharset()); - - //attach files - $files = $this->mailOptions->getMessageOptions()->getAttachments()->getFiles(); - $mailService->addAttachments($files); - - //attach files from dir - $dir = $this->mailOptions->getMessageOptions()->getAttachments()->getDir(); - - if ($dir['iterate'] === true && is_string($dir['path']) && is_dir($dir['path'])) { - $files = $dir['recursive'] === true - ? new RecursiveIteratorIterator( - new RecursiveDirectoryIterator( - $dir['path'], - FilesystemIterator::SKIP_DOTS - ), - RecursiveIteratorIterator::CHILD_FIRST - ) - : new DirectoryIterator($dir['path']); - - foreach ($files as $fileInfo) { - if ($fileInfo->isDir()) { - continue; - } - - $mailService->addAttachment($fileInfo->getPathname()); - } - } - - $this->attachMailListeners($mailService, $container); - return $mailService; - } - - protected function createMessage(): Email - { - $options = $this->mailOptions->getMessageOptions(); - $message = new Email(); - - $from = $options->getFrom(); - if (! empty($from)) { - $message->addFrom($from, $options->getFromName()); - } - - $replyTo = $options->getReplyTo(); - if (! empty($replyTo)) { - $message->setReplyTo($replyTo, $options->getReplyToName()); - } - - $to = $options->getTo(); - if (! empty($to)) { - $message->setTo($to); - } - - $cc = $options->getCc(); - if (! empty($cc)) { - $message->setCc($cc); - } - - $bcc = $options->getBcc(); - if (! empty($bcc)) { - $message->setBcc($bcc); - } - - return $message; - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function createTransport(ContainerInterface $container): TransportInterface - { - $adapter = $this->mailOptions->getTransport(); - if ($adapter instanceof TransportInterface) { - return $this->setupTransportConfig($adapter); - } - - //check is adapter is a service - if ($container->has($adapter)) { - $transport = $container->get($adapter); - if ($transport instanceof TransportInterface) { - return $this->setupTransportConfig($transport); - } else { - throw new InvalidArgumentException( - 'Provided transport service does not return a ' . TransportInterface::class . ' instance' - ); - } - } - - //check is the adapter is Symfony default adapter - if (is_subclass_of($adapter, TransportInterface::class)) { - return $this->setupTransportConfig(new $adapter()); - } - - //the adapter is not valid - throw exception - throw new InvalidArgumentException( - sprintf( - '"transport" must be a known alias, a container service or a class implementing %s; "%s" provided', - TransportInterface::class, - $adapter - ) - ); - } - - protected function setupTransportConfig(TransportInterface $transport): TransportInterface - { - if ($transport instanceof EsmtpTransport) { - $user = $this->mailOptions->getSmtpOptions()->getConnectionConfig()['username']; - $pass = rawurlencode($this->mailOptions->getSmtpOptions()->getConnectionConfig()['password']); - $tls = $this->mailOptions->getSmtpOptions()->getConnectionConfig()['tls'] === false ? 'false' : null; - $port = $this->mailOptions->getSmtpOptions()->getPort(); - $host = $this->mailOptions->getSmtpOptions()->getHost(); - $transport = Transport::fromDsn('smtp://' . $user . ':' . $pass . '@' . $host . ':' . $port - . '?auto_tls=' . $tls); - } - - return $transport; - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function attachMailListeners( - MailEventListenerAwareInterface $service, - ContainerInterface $container - ): void { - $listeners = $this->mailOptions->getEventListeners(); - foreach ($listeners as $listener) { - if (is_array($listener)) { - $type = $listener['type'] ?? ''; - $priority = $listener['priority'] ?? 1; - - $listener = $this->getListenerObject($container, $type); - $service->attachListener($listener, $priority); - } elseif (is_string($listener)) { - $type = $listener; - $priority = 1; - - $listener = $this->getListenerObject($container, $type); - $service->attachListener($listener, $priority); - } - } - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function getListenerObject(ContainerInterface $container, string $type): MailEventListenerInterface - { - $listener = null; - if ($container->has($type)) { - $listener = $container->get($type); - } - - if (! $listener instanceof MailEventListenerInterface) { - throw new RuntimeException(sprintf( - 'Mail event listener "%s" must be an instance of `%s`, but `%s` was given', - $type, - MailEventListenerInterface::class, - is_object($listener) ? $listener::class : gettype($listener) - )); - } - - return $listener; - } -} diff --git a/src/Factory/MailServiceFactory.php b/src/Factory/MailServiceFactory.php new file mode 100644 index 0000000..0ab2f1f --- /dev/null +++ b/src/Factory/MailServiceFactory.php @@ -0,0 +1,230 @@ +` and configured under `dot_mail.services.`. + * Works with any PSR-11 container that accepts a factory per service key. + */ +class MailServiceFactory +{ + public const SPECIFIC_PART = 'service'; + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws InvalidArgumentException When the service is not configured or its transport is invalid. + * @throws RuntimeException When an event listener is invalid. + */ + public function __invoke( + ContainerInterface $container, + string $requestedName = MailConfig::DOT_MAIL_PART . '.' . self::SPECIFIC_PART . '.default' + ): MailServiceInterface { + $name = MailConfig::serviceName($requestedName, self::SPECIFIC_PART); + $mailOptions = new MailOptions(MailConfig::service($container, $name)); + + $logService = $container->get(LogServiceInterface::class); + $message = $this->createMessage($mailOptions); + $transport = $this->createTransport($mailOptions, $container); + $attachments = $mailOptions->getMessageOptions()->getAttachments()->getFiles(); + + $mailService = new MailService($logService, $message, $transport, $mailOptions, $attachments); + + $this->attachMailListeners($mailOptions, $mailService, $container); + return $mailService; + } + + protected function createMessage(MailOptions $mailOptions): Email + { + $options = $mailOptions->getMessageOptions(); + $message = new Email(); + + $from = $options->getFrom(); + if (! empty($from)) { + $message->addFrom($from, $options->getFromName()); + } + + $replyTo = $options->getReplyTo(); + if (! empty($replyTo)) { + $message->setReplyTo($replyTo, $options->getReplyToName()); + } + + $to = $options->getTo(); + if (! empty($to)) { + $message->setTo($to); + } + + $cc = $options->getCc(); + if (! empty($cc)) { + $message->setCc($cc); + } + + $bcc = $options->getBcc(); + if (! empty($bcc)) { + $message->setBcc($bcc); + } + + $message->subject($options->getSubject()); + + $body = $options->getBody(); + if ($body->getContent() !== '') { + $message->html($body->getContent(), $body->getCharset()); + } + + return $message; + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function createTransport(MailOptions $mailOptions, ContainerInterface $container): TransportInterface + { + $adapter = $mailOptions->getTransport(); + + //a transport object provided by the user is used as it is + if ($adapter instanceof TransportInterface) { + return $adapter; + } + + //check is adapter is a service + if ($container->has($adapter)) { + $transport = $container->get($adapter); + if ($transport instanceof TransportInterface) { + return $transport; + } + + throw new InvalidArgumentException( + 'Provided transport service does not return a ' . TransportInterface::class . ' instance' + ); + } + + //the esmtp alias is configured from the smtp options + if ($adapter === EsmtpTransport::class) { + return $this->createEsmtpTransport($mailOptions); + } + + //check is the adapter is Symfony default adapter + if (is_subclass_of($adapter, TransportInterface::class)) { + return new $adapter(); + } + + //the adapter is not valid - throw exception + throw new InvalidArgumentException( + sprintf( + '"transport" must be a known alias, a container service or a class implementing %s; "%s" provided', + TransportInterface::class, + $adapter + ) + ); + } + + protected function createEsmtpTransport(MailOptions $mailOptions): EsmtpTransport + { + $smtp = $mailOptions->getSmtpOptions(); + $connection = $smtp->getConnectionConfig(); + $tls = $connection['tls'] ?? null; + + //null leaves the encryption to the transport (automatic), false disables it + $transport = new EsmtpTransport($smtp->getHost(), $smtp->getPort(), $tls === false ? false : null); + $transport->setAutoTls($tls !== false); + + $username = (string) ($connection['username'] ?? ''); + if ($username !== '') { + $transport->setUsername($username); + } + + $password = (string) ($connection['password'] ?? ''); + if ($password !== '') { + $transport->setPassword($password); + } + + $name = $smtp->getName(); + if ($name !== null) { + $transport->setLocalDomain($name); + } + + $timeLimit = $smtp->getConnectionTimeLimit(); + $stream = $transport->getStream(); + if ($timeLimit !== null && $stream instanceof SocketStream) { + $stream->setTimeout((float) $timeLimit); + } + + return $transport; + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function attachMailListeners( + MailOptions $mailOptions, + MailEventListenerAwareInterface $service, + ContainerInterface $container + ): void { + $listeners = $mailOptions->getEventListeners(); + foreach ($listeners as $listener) { + $type = is_array($listener) ? ($listener['type'] ?? null) : $listener; + $priority = is_array($listener) ? ($listener['priority'] ?? 1) : 1; + if (! is_string($type) || ! is_int($priority)) { + throw new RuntimeException(sprintf( + 'Mail event listener config must be a service name or ["type" => string, "priority" => int];' + . ' %s given', + get_debug_type($listener) + )); + } + + $service->attachListener($this->getListenerObject($container, $type), $priority); + } + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function getListenerObject(ContainerInterface $container, string $type): MailEventListenerInterface + { + $listener = null; + if ($container->has($type)) { + $listener = $container->get($type); + } + + if (! $listener instanceof MailEventListenerInterface) { + throw new RuntimeException(sprintf( + 'Mail event listener "%s" must be an instance of `%s`, but `%s` was given', + $type, + MailEventListenerInterface::class, + is_object($listener) ? $listener::class : gettype($listener) + )); + } + + return $listener; + } +} diff --git a/src/Options/AttachmentsOptions.php b/src/Options/AttachmentsOptions.php index a5bcdb9..d045f28 100644 --- a/src/Options/AttachmentsOptions.php +++ b/src/Options/AttachmentsOptions.php @@ -9,8 +9,7 @@ use function array_merge; /** - * @template TValue - * @template-extends AbstractOptions + * @extends AbstractOptions */ class AttachmentsOptions extends AbstractOptions { @@ -18,22 +17,33 @@ class AttachmentsOptions extends AbstractOptions public const DEFAULT_PATH = 'data/mail/attachments'; public const DEFAULT_RECURSIVE = false; + /** @var array */ protected array $files = []; - protected array $dir = [ + /** @var array{iterate: bool, path: string, recursive: bool} */ + protected array $dir = [ 'iterate' => self::DEFAULT_ITERATE, 'path' => self::DEFAULT_PATH, 'recursive' => self::DEFAULT_RECURSIVE, ]; + /** + * @return array{iterate: bool, path: string, recursive: bool} + */ public function getDir(): array { return $this->dir; } + /** + * @param array{iterate?: bool, path?: string, recursive?: bool} $dir + */ public function setDir(array $dir): void { - $this->dir = $dir; - $this->normalizeDirArray(); + $this->dir = [ + 'iterate' => $dir['iterate'] ?? self::DEFAULT_ITERATE, + 'path' => $dir['path'] ?? self::DEFAULT_PATH, + 'recursive' => $dir['recursive'] ?? self::DEFAULT_RECURSIVE, + ]; } /** @@ -52,11 +62,17 @@ protected function normalizeDirArray(): void } } + /** + * @return array + */ public function getFiles(): array { return $this->files; } + /** + * @param array $files + */ public function setFiles(array $files): void { $this->files = $files; @@ -67,6 +83,9 @@ public function addFile(string $filePath): void $this->files[] = $filePath; } + /** + * @param array $files + */ public function addFiles(array $files): void { $this->setFiles(array_merge($this->files, $files)); diff --git a/src/Options/BodyOptions.php b/src/Options/BodyOptions.php index ada0622..67e162d 100644 --- a/src/Options/BodyOptions.php +++ b/src/Options/BodyOptions.php @@ -8,8 +8,7 @@ use Laminas\Stdlib\AbstractOptions; /** - * @template TValue - * @template-extends AbstractOptions + * @extends AbstractOptions */ class BodyOptions extends AbstractOptions { diff --git a/src/Options/MailOptions.php b/src/Options/MailOptions.php index 7da067c..fc05161 100644 --- a/src/Options/MailOptions.php +++ b/src/Options/MailOptions.php @@ -15,25 +15,32 @@ use function strtolower; /** - * @template TValue - * @template-extends AbstractOptions + * @extends AbstractOptions */ class MailOptions extends AbstractOptions { + /** @var list */ protected array $eventListeners = []; - protected TransportInterface|string $transport = EsmtpTransport::class; - protected array $transportMap = [ + protected TransportInterface|string $transport = SendmailTransport::class; + /** @var array>> */ + protected array $transportMap = [ 'esmtp' => [EsmtpTransport::class], 'sendmail' => [SendmailTransport::class], ]; protected MessageOptions $messageOptions; protected SmtpOptions $smtpOptions; + /** + * @return array>> + */ public function getTransportMap(): array { return $this->transportMap; } + /** + * @param array>> $transportMap + */ public function setTransportMap(array $transportMap): void { $this->transportMap = $transportMap; @@ -61,9 +68,15 @@ public function setTransport(string|TransportInterface $transport): void public function getMessageOptions(): MessageOptions { + if (! isset($this->messageOptions)) { + $this->messageOptions = new MessageOptions(); + } return $this->messageOptions; } + /** + * @param array $messageOptions + */ public function setMessageOptions(array $messageOptions): void { $this->messageOptions = new MessageOptions($messageOptions); @@ -71,19 +84,31 @@ public function setMessageOptions(array $messageOptions): void public function getSmtpOptions(): SmtpOptions { + if (! isset($this->smtpOptions)) { + $this->smtpOptions = new SmtpOptions(); + } return $this->smtpOptions; } + /** + * @param array $smtpOptions + */ public function setSmtpOptions(array $smtpOptions): void { $this->smtpOptions = new SmtpOptions($smtpOptions); } + /** + * @return list + */ public function getEventListeners(): array { return $this->eventListeners; } + /** + * @param list $eventListeners + */ public function setEventListeners(array $eventListeners): void { $this->eventListeners = $eventListeners; diff --git a/src/Options/MessageOptions.php b/src/Options/MessageOptions.php index 4076bad..8522126 100644 --- a/src/Options/MessageOptions.php +++ b/src/Options/MessageOptions.php @@ -7,8 +7,7 @@ use Laminas\Stdlib\AbstractOptions; /** - * @template TValue - * @template-extends AbstractOptions + * @extends AbstractOptions */ class MessageOptions extends AbstractOptions { @@ -16,10 +15,13 @@ class MessageOptions extends AbstractOptions protected string $fromName = ''; protected string $replyTo = ''; protected string $replyToName = ''; - protected array $to = []; - protected array $cc = []; - protected array $bcc = []; - protected string $subject = ''; + /** @var string[] */ + protected array $to = []; + /** @var string[] */ + protected array $cc = []; + /** @var string[] */ + protected array $bcc = []; + protected string $subject = ''; protected BodyOptions $body; protected AttachmentsOptions $attachments; @@ -63,31 +65,49 @@ public function setReplyToName(string $replyToName): void $this->replyToName = $replyToName; } + /** + * @return string[] + */ public function getTo(): array { return $this->to; } + /** + * @param string[] $to + */ public function setTo(array $to): void { $this->to = $to; } + /** + * @return string[] + */ public function getCc(): array { return $this->cc; } + /** + * @param string[] $cc + */ public function setCc(array $cc): void { $this->cc = $cc; } + /** + * @return string[] + */ public function getBcc(): array { return $this->bcc; } + /** + * @param string[] $bcc + */ public function setBcc(array $bcc): void { $this->bcc = $bcc; @@ -105,9 +125,15 @@ public function setSubject(string $subject): void public function getBody(): BodyOptions { + if (! isset($this->body)) { + $this->body = new BodyOptions(); + } return $this->body; } + /** + * @param array $body + */ public function setBody(array $body): void { $this->body = new BodyOptions($body); @@ -115,9 +141,15 @@ public function setBody(array $body): void public function getAttachments(): AttachmentsOptions { + if (! isset($this->attachments)) { + $this->attachments = new AttachmentsOptions(); + } return $this->attachments; } + /** + * @param array $attachments + */ public function setAttachments(array $attachments): void { $this->attachments = new AttachmentsOptions($attachments); diff --git a/src/Options/SmtpOptions.php b/src/Options/SmtpOptions.php index be8ccf0..b119c01 100644 --- a/src/Options/SmtpOptions.php +++ b/src/Options/SmtpOptions.php @@ -10,26 +10,27 @@ use function sprintf; /** - * @extends AbstractOptions + * @extends AbstractOptions */ class SmtpOptions extends AbstractOptions { - protected string $name = 'localhost'; + protected ?string $name = null; + /** @var array{username?: string, password?: string, tls?: bool|null} */ protected array $connectionConfig = []; protected string $host = '127.0.0.1'; protected int $port = 25; - protected ?int $connectionTimeLimit; + protected ?int $connectionTimeLimit = null; - public function getName(): string + public function getName(): ?string { return $this->name; } /** - * Set the local client hostname or IP + * Set the local client hostname or IP; when null, the transport's own default is kept */ - public function setName(string $name): static + public function setName(?string $name): static { $this->name = $name; return $this; @@ -37,6 +38,8 @@ public function setName(string $name): static /** * Get connection configuration array + * + * @return array{username?: string, password?: string, tls?: bool|null} */ public function getConnectionConfig(): array { @@ -45,6 +48,8 @@ public function getConnectionConfig(): array /** * Set connection configuration array + * + * @param array{username?: string, password?: string, tls?: bool|null} $connectionConfig */ public function setConnectionConfig(array $connectionConfig): static { diff --git a/src/Result/MailResult.php b/src/Result/MailResult.php index 07a6028..5de6e9a 100644 --- a/src/Result/MailResult.php +++ b/src/Result/MailResult.php @@ -4,7 +4,7 @@ namespace Dot\Mail\Result; -use Exception; +use Throwable; class MailResult implements ResultInterface { @@ -12,12 +12,12 @@ class MailResult implements ResultInterface protected bool $valid; protected string $message; - protected Exception|null $exception; + protected Throwable|null $exception; public function __construct( bool $valid = true, string $message = self::DEFAULT_MESSAGE, - ?Exception $exception = null + ?Throwable $exception = null ) { $this->valid = $valid; $this->message = $message; @@ -36,10 +36,10 @@ public function isValid(): bool public function hasException(): bool { - return $this->exception instanceof Exception; + return $this->exception instanceof Throwable; } - public function getException(): ?Exception + public function getException(): ?Throwable { return $this->exception; } diff --git a/src/Result/ResultInterface.php b/src/Result/ResultInterface.php index 9e84413..3d56ebe 100644 --- a/src/Result/ResultInterface.php +++ b/src/Result/ResultInterface.php @@ -4,7 +4,7 @@ namespace Dot\Mail\Result; -use Exception; +use Throwable; interface ResultInterface { @@ -14,5 +14,5 @@ public function isValid(): bool; public function hasException(): bool; - public function getException(): ?Exception; + public function getException(): ?Throwable; } diff --git a/src/Service/LogService.php b/src/Service/LogService.php index 02e4290..4c84c1a 100644 --- a/src/Service/LogService.php +++ b/src/Service/LogService.php @@ -6,22 +6,28 @@ use DateTimeImmutable; use Dot\Mail\Email; +use Symfony\Component\Mime\Address; use function dirname; -use function file_exists; use function file_put_contents; +use function is_dir; use function json_encode; use function mkdir; use function sprintf; use function trim; use const FILE_APPEND; +use const LOCK_EX; use const PHP_EOL; class LogService implements LogServiceInterface { + /** @var array */ protected array $config = []; + /** + * @param array $config the dot_mail configuration + */ public function __construct(array $config) { $this->config = $config; @@ -43,8 +49,8 @@ public function sent(Email $message): false|int|null */ $dirname = dirname($target); - if (! file_exists($dirname)) { - mkdir($dirname, 0755, true); + if (! is_dir($dirname) && ! @mkdir($dirname, 0755, true) && ! is_dir($dirname)) { + return false; } /** @@ -63,9 +69,13 @@ public function sent(Email $message): false|int|null /** * Write the log data and return the result */ - return file_put_contents($target, $data, FILE_APPEND); + return file_put_contents($target, $data, FILE_APPEND | LOCK_EX); } + /** + * @param Address[] $addressList + * @return string[] + */ public function extractAddresses(array $addressList): array { $addresses = []; diff --git a/src/Service/MailService.php b/src/Service/MailService.php index da943a0..e6b948d 100644 --- a/src/Service/MailService.php +++ b/src/Service/MailService.php @@ -4,6 +4,7 @@ namespace Dot\Mail\Service; +use DirectoryIterator; use Dot\Mail\Email; use Dot\Mail\Event\MailEvent; use Dot\Mail\Event\MailEventListenerAwareInterface; @@ -12,19 +13,26 @@ use Dot\Mail\Options\MailOptions; use Dot\Mail\Result\MailResult; use Dot\Mail\Result\ResultInterface; -use Exception; -use Symfony\Component\Mailer\Exception\TransportExceptionInterface; +use FilesystemIterator; +use RecursiveCallbackFilterIterator; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; +use SplFileInfo; use Symfony\Component\Mailer\Transport\TransportInterface; use Symfony\Component\Mime\Part\AbstractPart; use Symfony\Component\Mime\Part\DataPart; use Symfony\Component\Mime\Part\Multipart\MixedPart; +use Throwable; use function array_merge; use function basename; use function count; -use function fopen; +use function is_dir; use function is_file; +use function is_readable; use function is_string; +use function sprintf; +use function str_starts_with; class MailService implements MailServiceInterface, MailEventListenerAwareInterface { @@ -32,59 +40,83 @@ class MailService implements MailServiceInterface, MailEventListenerAwareInterfa protected LogServiceInterface $logService; protected Email $message; + protected Email $prototype; protected TransportInterface $transport; protected MailOptions $mailOptions; + /** @var array */ protected array $attachments = []; + /** @var array */ + protected array $defaultAttachments = []; + /** + * @param array $attachments The default attachments, restored by reset() after every send + */ public function __construct( LogServiceInterface $logService, Email $message, TransportInterface $transport, - MailOptions $mailOptions + MailOptions $mailOptions, + array $attachments = [] ) { - $this->logService = $logService; - $this->message = $message; - $this->transport = $transport; - $this->mailOptions = $mailOptions; + $this->logService = $logService; + $this->message = $message; + $this->prototype = clone $message; + $this->transport = $transport; + $this->mailOptions = $mailOptions; + $this->attachments = $attachments; + $this->defaultAttachments = $attachments; } /** - * @throws MailException|TransportExceptionInterface + * Sends the current message, then restores the configured defaults (see reset()). + * Recipients, subject, body and attachments must be set again for every message. + * An exception thrown by a post-send listener propagates unchanged: the message was already delivered. + * + * @throws MailException */ public function send(): ResultInterface { $result = new MailResult(); - $this->message->setEncoding('utf-8'); + if ($this->message->getEncoding() === null) { + $this->message->setEncoding(self::DEFAULT_CHARSET); + } + try { $this->getEventManager()->triggerEvent($this->createMailEvent()); //attach files before sending $this->attachFiles(); $this->getTransport()->send($this->getMessage()); - $this->getMessage()->setBody(null); - - $this->getEventManager()->triggerEvent($this->createMailEvent(MailEvent::EVENT_MAIL_POST_SEND, $result)); - } catch (Exception $e) { + } catch (Throwable $e) { $result = $this->createMailResultFromException($e); - //trigger error event - $this->getEventManager()->triggerEvent($this->createMailEvent(MailEvent::EVENT_MAIL_SEND_ERROR, $result)); - throw new MailException($result->getMessage()); - } finally { - // Reset the Symfony Message body after every send attempt (success or failure). - // attachFiles() embeds DataParts into Message::$body; without this reset those - // DataParts survive a failed send and get wrapped into the next email's body, - // causing attachments from a failed send to leak into subsequent emails. - $this->getMessage()->setBody(null); + try { + //trigger error event + $this->getEventManager()->triggerEvent( + $this->createMailEvent(MailEvent::EVENT_MAIL_SEND_ERROR, $result) + ); + } finally { + $this->reset(); + } + throw new MailException($result->getMessage(), (int) $e->getCode(), $e); } - if ($result->isValid()) { - $this->logService->sent($this->getMessage()); + try { + $this->logSent(); + $this->getEventManager()->triggerEvent($this->createMailEvent(MailEvent::EVENT_MAIL_POST_SEND, $result)); + } finally { + $this->reset(); } return $result; } + public function reset(): void + { + $this->message = clone $this->prototype; + $this->attachments = $this->defaultAttachments; + } + public function createMailEvent( string $name = MailEvent::EVENT_MAIL_PRE_SEND, ?ResultInterface $result = null @@ -96,26 +128,30 @@ public function createMailEvent( return $event; } + /** + * @throws MailException When an attachment does not exist or is not readable. + */ public function attachFiles(): false|Email { - if (count($this->attachments) === 0) { + $attachments = array_merge($this->attachments, $this->getDirectoryAttachments()); + if (count($attachments) === 0) { return false; } $body = $this->message->getBody(); $parts = []; - foreach ($this->attachments as $key => $attachment) { - if (! is_file($attachment)) { - continue; + foreach ($attachments as $key => $attachment) { + if (! is_file($attachment) || ! is_readable($attachment)) { + throw new MailException( + sprintf('Attachment "%s" does not exist or is not readable', $attachment) + ); } $basename = is_string($key) ? $key : basename($attachment); - $parts[] = new DataPart(fopen($attachment, 'r'), $basename); + $parts[] = DataPart::fromPath($attachment, $basename); } - if (count($parts) > 0) { - $this->message->setBody(new MixedPart($body, ...$parts)); - } + $this->message->setBody(new MixedPart($body, ...$parts)); return $this->message; } @@ -123,13 +159,13 @@ public function attachFiles(): false|Email public function setBody(string|AbstractPart $body, ?string $charset = null): void { if (is_string($body)) { - $this->message->html($body); + $this->message->html($body, $charset ?? self::DEFAULT_CHARSET); } else { $this->message->setBody($body); } } - public function createMailResultFromException(Exception $e): ResultInterface + public function createMailResultFromException(Throwable $e): ResultInterface { return new MailResult(false, $e->getMessage(), $e); } @@ -153,16 +189,25 @@ public function addAttachment(string $path, ?string $filename = null): void } } + /** + * @param array $paths + */ public function addAttachments(array $paths): void { $this->setAttachments(array_merge($this->attachments, $paths)); } + /** + * @return array + */ public function getAttachments(): array { return $this->attachments; } + /** + * @param array $paths + */ public function setAttachments(array $paths): void { $this->attachments = $paths; @@ -177,4 +222,53 @@ public function setTransport(TransportInterface $transport): void { $this->transport = $transport; } + + /** + * A failed log write must never turn a delivered email into an error + */ + protected function logSent(): void + { + try { + $this->logService->sent($this->getMessage()); + } catch (Throwable) { + // intentionally ignored + } + } + + /** + * Collects the files of the configured attachments directory at send time. + * Relative paths are resolved against the current working directory; files and directories starting with a dot + * are skipped. + * + * @return string[] + */ + protected function getDirectoryAttachments(): array + { + $dir = $this->mailOptions->getMessageOptions()->getAttachments()->getDir(); + + if (($dir['iterate'] ?? false) !== true || ! is_string($dir['path'] ?? null) || ! is_dir($dir['path'])) { + return []; + } + + //hidden files and directories are skipped; a hidden directory is not descended into + $files = ($dir['recursive'] ?? false) === true + ? new RecursiveIteratorIterator( + new RecursiveCallbackFilterIterator( + new RecursiveDirectoryIterator($dir['path'], FilesystemIterator::SKIP_DOTS), + static fn (SplFileInfo $file): bool => ! str_starts_with($file->getFilename(), '.') + ) + ) + : new DirectoryIterator($dir['path']); + + $paths = []; + foreach ($files as $fileInfo) { + if ($fileInfo->isDir() || str_starts_with($fileInfo->getFilename(), '.')) { + continue; + } + + $paths[] = $fileInfo->getPathname(); + } + + return $paths; + } } diff --git a/src/Service/MailServiceInterface.php b/src/Service/MailServiceInterface.php index 5ebf83e..1b90f89 100644 --- a/src/Service/MailServiceInterface.php +++ b/src/Service/MailServiceInterface.php @@ -7,6 +7,7 @@ use Dot\Mail\Email; use Dot\Mail\Result\ResultInterface; use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Mime\Part\AbstractPart; interface MailServiceInterface { @@ -18,17 +19,36 @@ public function getMessage(): Email; public function getTransport(): TransportInterface; - public function setBody(string $body, ?string $charset = null): void; + /** + * Sets the body: a string is used as HTML in the given charset (utf-8 by default), + * a MIME part is used as it is and the charset is ignored. + */ + public function setBody(string|AbstractPart $body, ?string $charset = null): void; public function setSubject(string $subject): void; public function addAttachment(string $path, ?string $filename = null): void; + /** + * @param array $paths file paths, optionally keyed by attachment name + */ public function addAttachments(array $paths): void; + /** + * @return array + */ public function getAttachments(): array; + /** + * @param array $paths file paths, optionally keyed by attachment name + */ public function setAttachments(array $paths): void; public function setTransport(TransportInterface $transport): void; + + /** + * Restores the message and attachments to the configured defaults. + * Called automatically after every send() attempt. + */ + public function reset(): void; } diff --git a/test/CommonTrait.php b/test/CommonTrait.php index e42f8f7..0846b0c 100644 --- a/test/CommonTrait.php +++ b/test/CommonTrait.php @@ -9,6 +9,7 @@ trait CommonTrait { + /** @var array */ protected array $config; protected vfsStreamDirectory $fileSystem; @@ -30,9 +31,12 @@ public function setup(): void $this->config = $this->generateConfig(); } + /** + * @return array + */ public function getConfig(): array { - return $this->getConfig(); + return $this->config; } public function getFileSystem(): vfsStreamDirectory @@ -40,59 +44,64 @@ public function getFileSystem(): vfsStreamDirectory return $this->fileSystem; } + /** + * @return array + */ private function generateConfig(): array { return [ 'dot_mail' => [ - 'default' => [ - 'message_options' => [ - 'from' => '', - 'from_name' => '', - 'reply_to' => '', - 'reply_to_name' => '', - 'to' => [], - 'cc' => [], - 'bcc' => [], - 'subject' => '', - 'body' => [ - 'content' => '', - 'charset' => 'utf-8', - ], - 'attachments' => [ - 'files' => [], - 'dir' => [ - 'iterate' => false, - 'path' => $this->fileSystem->url() . '/data/mail/attachments', - 'recursive' => false, + 'services' => [ + 'default' => [ + 'message_options' => [ + 'from' => '', + 'from_name' => '', + 'reply_to' => '', + 'reply_to_name' => '', + 'to' => [], + 'cc' => [], + 'bcc' => [], + 'subject' => '', + 'body' => [ + 'content' => '', + 'charset' => 'utf-8', + ], + 'attachments' => [ + 'files' => [], + 'dir' => [ + 'iterate' => false, + 'path' => $this->fileSystem->url() . '/data/mail/attachments', + 'recursive' => false, + ], ], ], - ], - /** - * the mail transport to use - * can be any class implementing Symfony\Component\Mailer\Transport\TransportInterface - * - * for standard mail transports, you can use these aliases - * - sendmail => Symfony\Component\Mailer\Transport\SendmailTransport - * - esmtp => Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport - * - * defaults to sendmail - **/ - 'transport' => 'esmtp', - //options that will be used only if Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport - // adapter is used - 'smtp_options' => [ - 'host' => 'testHost', - 'port' => 587, - 'connection_config' => [ - //the smtp authentication identity - 'username' => 'test', - //the smtp authentication credential - 'password' => 'testPassword', - 'tls' => null, + /** + * the mail transport to use + * can be any class implementing Symfony\Component\Mailer\Transport\TransportInterface + * + * for standard mail transports, you can use these aliases + * - sendmail => Symfony\Component\Mailer\Transport\SendmailTransport + * - esmtp => Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport + * + * defaults to sendmail + **/ + 'transport' => 'esmtp', + //options that will be used only if Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport + // adapter is used + 'smtp_options' => [ + 'host' => 'testHost', + 'port' => 587, + 'connection_config' => [ + //the smtp authentication identity + 'username' => 'test', + //the smtp authentication credential + 'password' => 'testPassword', + 'tls' => null, + ], ], ], + 'test' => 'string test', ], - 'test' => 'string test', // option to log the SENT emails 'log' => [ 'sent' => $this->fileSystem->url() . '/log/mail/sent.log', diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index cb4a0b8..9737368 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -6,14 +6,16 @@ use Dot\Mail\ConfigProvider; use Dot\Mail\Factory\LogServiceFactory; -use Dot\Mail\Factory\MailOptionsAbstractFactory; -use Dot\Mail\Factory\MailServiceAbstractFactory; +use Dot\Mail\Factory\MailOptionsFactory; +use Dot\Mail\Factory\MailServiceFactory; use Dot\Mail\Service\LogService; use Dot\Mail\Service\LogServiceInterface; +use Dot\Mail\Service\MailServiceInterface; use PHPUnit\Framework\TestCase; class ConfigProviderTest extends TestCase { + /** @var array */ private array $config; public function setUp(): void @@ -42,18 +44,22 @@ public function testDependenciesHasAliases(): void LogService::class, $this->config['dependencies']['aliases'][LogServiceInterface::class] ); + $this->assertSame( + 'dot-mail.service.default', + $this->config['dependencies']['aliases'][MailServiceInterface::class] + ); } - public function testDependenciesHasAbstractFactories(): void + public function testDefaultMailServiceIsRegistered(): void { - $this->assertArrayHasKey('abstract_factories', $this->config['dependencies']); - $this->assertContains( - MailServiceAbstractFactory::class, - $this->config['dependencies']['abstract_factories'] - ); - $this->assertContains( - MailOptionsAbstractFactory::class, - $this->config['dependencies']['abstract_factories'] - ); + $factories = $this->config['dependencies']['factories']; + + $this->assertSame(MailServiceFactory::class, $factories['dot-mail.service.default']); + $this->assertSame(MailOptionsFactory::class, $factories['dot-mail.options.default']); + } + + public function testNoAbstractFactoriesAreRegistered(): void + { + $this->assertArrayNotHasKey('abstract_factories', $this->config['dependencies']); } } diff --git a/test/EmailTest.php b/test/EmailTest.php index 3d4f871..78702a8 100644 --- a/test/EmailTest.php +++ b/test/EmailTest.php @@ -9,6 +9,8 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Exception\LogicException; +use Symfony\Component\Mime\Part\Multipart\AlternativePart; +use Symfony\Component\Mime\Part\TextPart; class EmailTest extends TestCase { @@ -85,4 +87,66 @@ public function testAddressObjectsInArraysAreKept(): void $this->assertCount(1, $cc); $this->assertSame('Copy', $cc[0]->getName()); } + + public function testTextOnlyMessageHasOnlyTextPart(): void + { + $subject = new Email(); + $subject->text('plain text'); + + $body = $subject->getBody(); + $this->assertSame(TextPart::class, $body::class); + $this->assertSame('plain text', $body->getBody()); + } + + public function testTextAndHtmlMessageIsAlternative(): void + { + $subject = new Email(); + $subject->text('plain text'); + $subject->html('

html

'); + + $this->assertInstanceOf(AlternativePart::class, $subject->getBody()); + } + + public function testMessageWithoutBodyIsInvalid(): void + { + $subject = new Email(); + $subject->setFrom('from@example.com'); + $subject->setTo('to@example.com'); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('A message must have a text or an HTML part.'); + $subject->ensureValidity(); + } + + public function testPriorityIsReadFromTheHeader(): void + { + $this->assertSame(Email::PRIORITY_NORMAL, (new Email())->getPriority()); + + foreach ([1, 2, 3, 4, 5] as $priority) { + $this->assertSame($priority, (new Email())->priority($priority)->getPriority()); + } + + $this->assertSame(Email::PRIORITY_LOWEST, (new Email())->priority(9)->getPriority()); + $this->assertSame(Email::PRIORITY_HIGHEST, (new Email())->priority(0)->getPriority()); + + $malformed = new Email(); + $malformed->getHeaders()->addTextHeader('X-Priority', 'x'); + $this->assertSame(Email::PRIORITY_NORMAL, $malformed->getPriority()); + } + + public function testSenderAcceptsAnAddressObject(): void + { + $email = (new Email())->setSender(new Address('sender@example.com', 'Sender Name')); + + $this->assertSame('sender@example.com', $email->getSender()?->getAddress()); + $this->assertSame('Sender Name', $email->getSender()->getName()); + } + + public function testSenderAcceptsAStringAndName(): void + { + $email = (new Email())->setSender('sender@example.com', 'Sender Name'); + + $this->assertSame('sender@example.com', $email->getSender()?->getAddress()); + $this->assertSame('Sender Name', $email->getSender()->getName()); + } } diff --git a/test/Event/MailEventListenerTest.php b/test/Event/MailEventListenerTest.php index fd8c686..009d272 100644 --- a/test/Event/MailEventListenerTest.php +++ b/test/Event/MailEventListenerTest.php @@ -6,7 +6,6 @@ use Dot\Mail\Event\MailEventListenerAwareTrait; use Dot\Mail\Event\MailEventListenerInterface; -use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\TestCase; use ReflectionException; use ReflectionObject; @@ -14,7 +13,6 @@ class MailEventListenerTest extends TestCase { /** - * @throws Exception * @throws ReflectionException */ public function testListenerDetachingAndClearing(): void @@ -22,8 +20,8 @@ public function testListenerDetachingAndClearing(): void $trait = new class { use MailEventListenerAwareTrait; }; - $listener1 = $this->createMock(MailEventListenerInterface::class); - $listener2 = $this->createMock(MailEventListenerInterface::class); + $listener1 = $this->createStub(MailEventListenerInterface::class); + $listener2 = $this->createStub(MailEventListenerInterface::class); $trait->attachListener($listener1, 10); $trait->attachListener($listener2); @@ -45,7 +43,6 @@ public function testListenerDetachingAndClearing(): void } /** - * @throws Exception * @throws ReflectionException */ public function testDetachingUnknownListenerKeepsOthers(): void @@ -53,8 +50,8 @@ public function testDetachingUnknownListenerKeepsOthers(): void $trait = new class { use MailEventListenerAwareTrait; }; - $attached = $this->createMock(MailEventListenerInterface::class); - $unknown = $this->createMock(MailEventListenerInterface::class); + $attached = $this->createStub(MailEventListenerInterface::class); + $unknown = $this->createStub(MailEventListenerInterface::class); $trait->attachListener($attached); $trait->detachListener($unknown); diff --git a/test/Event/MailEventTest.php b/test/Event/MailEventTest.php index d6323be..fad5736 100644 --- a/test/Event/MailEventTest.php +++ b/test/Event/MailEventTest.php @@ -5,26 +5,20 @@ namespace DotTest\Mail\Event; use Dot\Mail\Event\MailEvent; +use Dot\Mail\Result\MailResult; use Dot\Mail\Service\MailServiceInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; class MailEventTest extends TestCase { - private MailServiceInterface|MockObject $mailService; + private MailServiceInterface&Stub $mailService; - /** - * @throws Exception - */ public function setUp(): void { - $this->mailService = $this->createMock(MailServiceInterface::class); + $this->mailService = $this->createStub(MailServiceInterface::class); } - /** - * @throws Exception - */ public function testMailEventCanBeCreated(): void { $defaultMailEvent = new MailEvent($this->mailService); @@ -33,12 +27,12 @@ public function testMailEventCanBeCreated(): void $this->assertContainsOnlyInstancesOf(MailServiceInterface::class, [$defaultMailEvent->getMailService()]); $customMailEvent = new MailEvent($this->mailService, MailEvent::EVENT_MAIL_SEND_ERROR); - $mailServiceInterface = $this->createMock(MailServiceInterface::class); + $mailServiceInterface = $this->createStub(MailServiceInterface::class); $customMailEvent->setMailService($mailServiceInterface); $this->assertContainsOnlyInstancesOf(MailEvent::class, [$customMailEvent]); $this->assertSame(MailEvent::EVENT_MAIL_SEND_ERROR, $customMailEvent->getName()); - $this->assertContainsOnlyInstancesOf(MailServiceInterface::class, [$customMailEvent->getMailService()]); + $this->assertSame($mailServiceInterface, $customMailEvent->getMailService()); } public function testEventPropagation(): void @@ -48,4 +42,14 @@ public function testEventPropagation(): void $event->stopPropagation(); $this->assertTrue($event->propagationIsStopped()); } + + public function testResultIsNullUntilSet(): void + { + $event = new MailEvent($this->mailService); + $this->assertNull($event->getResult()); + + $result = new MailResult(); + $event->setResult($result); + $this->assertSame($result, $event->getResult()); + } } diff --git a/test/Factory/AbstractMailFactoryTest.php b/test/Factory/AbstractMailFactoryTest.php deleted file mode 100644 index 319a6b5..0000000 --- a/test/Factory/AbstractMailFactoryTest.php +++ /dev/null @@ -1,105 +0,0 @@ -fileSystem = vfsStream::setup('root', 0644, [ - 'log' => ['mail'], - 'data' => [ - 'mail' => [ - 'attachments' => [ - 'testPdfAttachment.pdf' => 'pdf content', - 'testXlsAttachment.xls' => 'xls content', - ], - 'output' => [], - ], - ], - ]); - - $this->config = $this->generateConfig(); - $this->subject = new class extends AbstractMailFactory { - public const SPECIFIC_PART = 'testPart'; - - /** - * @param string $requestedName - */ - public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): MailOptions - { - return new MailOptions(); - } - }; - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testCanCreateRequestedService(): void - { - $container = $this->createMock(ContainerInterface::class); - $requestedName = 'dot-mail.testPart.default'; - $container->expects($this->once())->method('get')->willReturn($this->config); - - $result = $this->subject->canCreate($container, $requestedName); - $this->assertTrue($result); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateRequestedNameFromWrongParts(): void - { - $container = $this->createMock(ContainerInterface::class); - $requestedName = 'dot-mail.testPart.default.test'; - - $result = $this->subject->canCreate($container, $requestedName); - $this->assertFalse($result); - } - - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateRequestedNameWithoutParts(): void - { - $container = $this->createMock(ContainerInterface::class); - - set_error_handler(static function (int $severity, string $message): never { - throw new ErrorException($message, 0, $severity); - }); - - try { - $this->assertFalse($this->subject->canCreate($container, 'dot-mail')); - $this->assertFalse($this->subject->canCreate($container, 'dot-mail.testPart')); - } finally { - restore_error_handler(); - } - } -} diff --git a/test/Factory/LogServiceFactoryTest.php b/test/Factory/LogServiceFactoryTest.php index 279a524..0ef606e 100644 --- a/test/Factory/LogServiceFactoryTest.php +++ b/test/Factory/LogServiceFactoryTest.php @@ -7,29 +7,48 @@ use Dot\Mail\Email; use Dot\Mail\Factory\LogServiceFactory; use Dot\Mail\Service\LogService; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Mail\Fixture\InMemoryContainer; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function dirname; +use function rmdir; +use function sys_get_temp_dir; +use function uniqid; +use function unlink; + class LogServiceFactoryTest extends TestCase { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception */ public function testServiceCreatedWithoutValidConfig(): void { - $message = $this->createMock(Email::class); - $container = $this->createMock(ContainerInterface::class); + $container = new InMemoryContainer(['config' => ['test' => 'invalid data']]); $logService = (new LogServiceFactory())($container); - $container->method('get')->with('config')->willReturn(['test' => 'invalid data']); - $this->assertInstanceOf(LogService::class, $logService); // if no valid config, logging will be disabled - $this->assertNull($logService->sent($message)); + $this->assertNull($logService->sent(new Email())); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testServiceUsesTheDotMailLogTarget(): void + { + $target = sys_get_temp_dir() . '/dot-mail-test-' . uniqid() . '/sent.log'; + $container = new InMemoryContainer(['config' => ['dot_mail' => ['log' => ['sent' => $target]]]]); + $logService = (new LogServiceFactory())($container); + + $message = (new Email())->subject('Logged'); + $this->assertIsInt($logService->sent($message)); + $this->assertFileExists($target); + + unlink($target); + rmdir(dirname($target)); } } diff --git a/test/Factory/MailConfigTest.php b/test/Factory/MailConfigTest.php new file mode 100644 index 0000000..5754168 --- /dev/null +++ b/test/Factory/MailConfigTest.php @@ -0,0 +1,125 @@ +assertSame('default', MailConfig::serviceName('dot-mail.service.default', 'service')); + $this->assertSame('newsletter', MailConfig::serviceName('dot-mail.options.newsletter', 'options')); + } + + public function testMalformedKeysAreRejected(): void + { + $keys = [ + 'dot-mail', + 'dot-mail.service', + 'dot-mail.service.', + 'dot-mail.service.default.extra', + 'other.service.default', + 'dot-mail.options.default', + ]; + + foreach ($keys as $key) { + try { + MailConfig::serviceName($key, 'service'); + $this->fail('Expected InvalidArgumentException for ' . $key); + } catch (InvalidArgumentException $e) { + $this->assertStringContainsString('"dot-mail.service."', $e->getMessage(), $key); + } + } + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testServicesComeOnlyFromTheServicesKey(): void + { + $container = new InMemoryContainer([ + 'config' => [ + 'dot_mail' => [ + 'log' => ['sent' => '/tmp/sent.log'], + 'services' => ['log' => ['transport' => 'sendmail'], 'other' => []], + ], + ], + ]); + + $this->assertSame(['log', 'other'], array_keys(MailConfig::services($container))); + $this->assertSame(['transport' => 'sendmail'], MailConfig::service($container, 'log')); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testOldConfigurationLayoutIsRejected(): void + { + $container = new InMemoryContainer([ + 'config' => [ + 'dot_mail' => [ + 'default' => ['transport' => 'sendmail'], + 'log' => ['sent' => '/tmp/sent.log'], + ], + ], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Mail service "default" must be configured under "dot_mail.services"'); + MailConfig::services($container); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testConfigurationWithOnlyLogHasNoServices(): void + { + $container = new InMemoryContainer(['config' => ['dot_mail' => ['log' => ['sent' => '/tmp/sent.log']]]]); + + $this->assertSame([], MailConfig::services($container)); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testMissingConfigurationHasNoServices(): void + { + $this->assertSame([], MailConfig::services(new InMemoryContainer())); + $this->assertSame([], MailConfig::services(new InMemoryContainer(['config' => ['other' => []]]))); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testUnconfiguredOrInvalidServiceIsRejected(): void + { + $container = new InMemoryContainer(['config' => ['dot_mail' => ['services' => ['text' => 'not an array']]]]); + + foreach (['missing', 'text'] as $name) { + try { + MailConfig::service($container, $name); + $this->fail('Expected InvalidArgumentException for ' . $name); + } catch (InvalidArgumentException $e) { + $this->assertSame( + 'Mail service "' . $name . '" is not configured under "dot_mail.services"', + $e->getMessage() + ); + } + } + } +} diff --git a/test/Factory/MailOptionsAbstractFactoryTest.php b/test/Factory/MailOptionsAbstractFactoryTest.php deleted file mode 100644 index cdf2840..0000000 --- a/test/Factory/MailOptionsAbstractFactoryTest.php +++ /dev/null @@ -1,78 +0,0 @@ -fileSystem = vfsStream::setup('root', 0644, [ - 'log' => ['mail'], - 'data' => [ - 'mail' => [ - 'attachments' => [ - 'testPdfAttachment.pdf' => 'pdf content', - 'testXlsAttachment.xls' => 'xls content', - ], - 'output' => [], - ], - ], - ]); - - $this->config = $this->generateConfig(); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testGeneratesMailOptions(): void - { - $defaultName = 'dot-mail.options.default'; - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn($this->config); - - $subject = (new MailOptionsAbstractFactory())($container, $defaultName); - - $this->assertContainsOnlyInstancesOf(MailOptions::class, [$subject]); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testIsSpecificConfigArray(): void - { - $defaultName = 'dot-mail.options.test'; - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn($this->config); - - $subject = (new MailOptionsAbstractFactory())($container, $defaultName); - - $this->assertContainsOnlyInstancesOf(MailOptions::class, [$subject]); - } -} diff --git a/test/Factory/MailOptionsFactoryTest.php b/test/Factory/MailOptionsFactoryTest.php new file mode 100644 index 0000000..29e4dcd --- /dev/null +++ b/test/Factory/MailOptionsFactoryTest.php @@ -0,0 +1,97 @@ +fileSystem = vfsStream::setup('root', 0644, [ + 'log' => ['mail'], + 'data' => [ + 'mail' => [ + 'attachments' => [ + 'testPdfAttachment.pdf' => 'pdf content', + 'testXlsAttachment.xls' => 'xls content', + ], + 'output' => [], + ], + ], + ]); + + $this->config = $this->generateConfig(); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testGeneratesMailOptions(): void + { + $defaultName = 'dot-mail.options.default'; + $container = new InMemoryContainer(['config' => $this->config]); + + $subject = (new MailOptionsFactory())($container, $defaultName); + + $this->assertContainsOnlyInstancesOf(MailOptions::class, [$subject]); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testNonArrayServiceConfigThrows(): void + { + $container = new InMemoryContainer(['config' => $this->config]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Mail service "test" is not configured under "dot_mail.services"'); + (new MailOptionsFactory())($container, 'dot-mail.options.test'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testUnconfiguredServiceThrows(): void + { + $container = new InMemoryContainer(['config' => $this->config]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Mail service "missing" is not configured under "dot_mail.services"'); + (new MailOptionsFactory())($container, 'dot-mail.options.missing'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testDefaultServiceIsUsedWithoutARequestedName(): void + { + $container = new InMemoryContainer([ + 'config' => [ + 'dot_mail' => ['services' => ['default' => ['transport' => 'esmtp']]], + ], + ]); + + $this->assertSame( + EsmtpTransport::class, + (new MailOptionsFactory())($container)->getTransport() + ); + } +} diff --git a/test/Factory/MailServiceAbstractFactoryTest.php b/test/Factory/MailServiceAbstractFactoryTest.php deleted file mode 100644 index 0519efb..0000000 --- a/test/Factory/MailServiceAbstractFactoryTest.php +++ /dev/null @@ -1,265 +0,0 @@ -fileSystem = vfsStream::setup('root', 0644, [ - 'log' => ['mail'], - 'data' => [ - 'mail' => [ - 'attachments' => [ - 'testPdfAttachment.pdf' => 'pdf content', - 'testXlsAttachment.xls' => 'xls content', - ], - 'output' => [], - ], - ], - ]); - - $this->container = $this->createMock(ContainerInterface::class); - $this->mailOptions = $this->createMock(MailOptions::class); - $this->smtpOptions = $this->createMock(SmtpOptions::class); - $this->messageOptions = $this->createMock(MessageOptions::class); - $this->attachmentsOptions = $this->createMock(AttachmentsOptions::class); - - $this->config = $this->generateConfig(); - $this->subject = new Subject(); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testGenerateServiceWithProvidedAdapter(): void - { - $requestedName = 'dot-mail.service.default'; - - $this->attachmentsOptions->expects($this->any()) - ->method('getFiles') - ->willReturn(['testPdfAttachment.pdf', 'testXlsAttachment.xls']); - $this->attachmentsOptions->expects($this->any()) - ->method('getDir') - ->willReturn([ - 'iterate' => true, - 'path' => $this->fileSystem->url() . '/data/mail/attachments', - 'recursive' => true, - ]); - $this->messageOptions->expects($this->any()) - ->method('getAttachments') - ->willReturn($this->attachmentsOptions); - $this->mailOptions->expects($this->any()) - ->method('getMessageOptions') - ->willReturn($this->messageOptions); - $this->mailOptions->expects($this->any()) - ->method('getTransport') - ->willReturn($this->createMock(EsmtpTransport::class)); - $this->mailOptions->expects($this->any()) - ->method('getEventListeners') - ->willReturn([AbstractMailEventListener::class]); - - $this->container->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap([ - ['dot-mail.options.default', $this->mailOptions], - [LogServiceInterface::class, $this->createMock(LogService::class)], - [ - AbstractMailEventListener::class, - new class extends AbstractMailEventListener { - }, - ], - ]); - $this->container->expects($this->once()) - ->method('has') - ->willReturn(true); - - $this->smtpOptions->expects($this->any()) - ->method('getConnectionConfig') - ->willReturn([ - 'username' => 'test', - 'password' => 'testPassword', - 'tls' => null, - ]); - - $this->smtpOptions->expects($this->once()) - ->method('getHost') - ->willReturn('localhost'); - - $this->mailOptions->expects($this->any()) - ->method('getSmtpOptions') - ->willReturn($this->smtpOptions); - - $mailService = ($this->subject)($this->container, $requestedName); - $this->assertInstanceOf(MailService::class, $mailService); - $this->assertInstanceOf(EsmtpTransport::class, $mailService->getTransport()); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testGenerateServiceWithoutProvidedAdapter(): void - { - $requestedName = 'dot-mail.service.default'; - - $this->attachmentsOptions->expects($this->any()) - ->method('getFiles') - ->willReturn(['testPdfAttachment.pdf', 'testXlsAttachment.xls']); - $this->attachmentsOptions->expects($this->any()) - ->method('getDir') - ->willReturn([ - 'iterate' => AttachmentsOptions::DEFAULT_ITERATE, - 'path' => AttachmentsOptions::DEFAULT_PATH, - 'recursive' => AttachmentsOptions::DEFAULT_RECURSIVE, - ]); - $this->messageOptions->expects($this->any()) - ->method('getAttachments') - ->willReturn($this->attachmentsOptions); - $this->mailOptions->expects($this->any()) - ->method('getMessageOptions') - ->willReturn($this->messageOptions); - $this->mailOptions->expects($this->any()) - ->method('getTransport') - ->willReturn(EsmtpTransport::class); - $this->mailOptions->expects($this->any()) - ->method('getEventListeners') - ->willReturn(['Invalid Listener Test']); - - $this->container->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap([ - ['dot-mail.options.default', $this->mailOptions], - [LogServiceInterface::class, $this->createMock(LogService::class)], - [EsmtpTransport::class, new EsmtpTransport()], - ['Invalid Listener Test', 'Invalid Listener provided'], - ]); - $this->container->expects($this->any()) - ->method('has') - ->willReturnMap([ - [EsmtpTransport::class, true], - ['Invalid Listener Test', true], - ]); - - $this->smtpOptions->expects($this->any()) - ->method('getConnectionConfig') - ->willReturn([ - 'username' => 'test', - 'password' => 'testPassword', - 'tls' => false, - ]); - - $this->smtpOptions->expects($this->once()) - ->method('getHost') - ->willReturn('localhost'); - - $this->mailOptions->expects($this->any()) - ->method('getSmtpOptions') - ->willReturn($this->smtpOptions); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Mail event listener "Invalid Listener Test" must be an instance of'); - - $mailService = ($this->subject)($this->container, $requestedName); - - $this->assertInstanceOf(MailService::class, $mailService); - $this->assertInstanceOf(EsmtpTransport::class, $mailService->getTransport()); - $this->assertCount(2, $mailService->getAttachments()); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testGenerateServiceInvalidAdapter(): void - { - $requestedName = 'dot-mail.service.default'; - - $this->mailOptions->expects($this->any()) - ->method('getTransport') - ->willReturn('test'); - - $this->container->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap([ - ['dot-mail.options.default', $this->mailOptions], - [LogServiceInterface::class, $this->createMock(LogService::class)], - ['Invalid Listener Test', 'Invalid Listener provided'], - ]); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessageMatches('/"transport" must be a known alias.*"test" provided/'); - ($this->subject)($this->container, $requestedName); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testGenerateServiceThrowException(): void - { - $requestedName = 'dot-mail.service.default'; - - $this->mailOptions->expects($this->any()) - ->method('getTransport') - ->willReturn(InvalidArgumentException::class); - - $this->container->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap([ - ['dot-mail.options.default', $this->mailOptions], - [LogServiceInterface::class, $this->createMock(LogService::class)], - [EsmtpTransport::class, new EsmtpTransport()], - ['Invalid Listener Test', 'Invalid Listener provided'], - ]); - $this->container->expects($this->any()) - ->method('has') - ->willReturnMap([ - [InvalidArgumentException::class, true], - ['Invalid Listener Test', true], - ]); - - $this->expectException(InvalidArgumentException::class); - ($this->subject)($this->container, $requestedName); - } -} diff --git a/test/Factory/MailServiceFactoryTest.php b/test/Factory/MailServiceFactoryTest.php new file mode 100644 index 0000000..0d66d4b --- /dev/null +++ b/test/Factory/MailServiceFactoryTest.php @@ -0,0 +1,457 @@ +fileSystem = vfsStream::setup('root', 0644, [ + 'log' => ['mail'], + 'data' => [ + 'mail' => [ + 'attachments' => [ + 'testPdfAttachment.pdf' => 'pdf content', + 'testXlsAttachment.xls' => 'xls content', + ], + 'output' => [], + ], + ], + ]); + + $this->config = $this->generateConfig(); + $this->subject = new Subject(); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testGenerateServiceWithProvidedAdapter(): void + { + $provided = new EsmtpTransport(); + $options = [ + 'transport' => $provided, + 'event_listeners' => [AbstractMailEventListener::class], + 'message_options' => [ + 'attachments' => [ + 'files' => ['testPdfAttachment.pdf', 'testXlsAttachment.xls'], + 'dir' => [ + 'iterate' => true, + 'path' => $this->fileSystem->url() . '/data/mail/attachments', + 'recursive' => true, + ], + ], + ], + ]; + + $container = $this->containerFor($options, [ + AbstractMailEventListener::class => new class extends AbstractMailEventListener { + }, + ]); + + $mailService = ($this->subject)($container, 'dot-mail.service.default'); + $this->assertInstanceOf(MailService::class, $mailService); + $this->assertSame($provided, $mailService->getTransport()); + $this->assertSame(['testPdfAttachment.pdf', 'testXlsAttachment.xls'], $mailService->getAttachments()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testTransportServiceFromTheContainerIsUsed(): void + { + $service = new EsmtpTransport('service.example.com', 25, false); + $options = ['transport' => 'mail.transport']; + $container = $this->containerFor($options, ['mail.transport' => $service]); + + $this->assertSame($service, ($this->subject)($container, 'dot-mail.service.default')->getTransport()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testInvalidListenerServiceThrows(): void + { + $options = [ + 'transport' => 'sendmail', + 'event_listeners' => ['Invalid Listener Test'], + ]; + $container = $this->containerFor($options, ['Invalid Listener Test' => 'Invalid Listener provided']); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Mail event listener "Invalid Listener Test" must be an instance of'); + ($this->subject)($container, 'dot-mail.service.default'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testInvalidListenerConfigThrows(): void + { + $listener = new class extends AbstractMailEventListener { + }; + $cases = [ + 'integer type' => [['type' => 123]], + 'missing type' => [['priority' => 2]], + 'string priority' => [['type' => 'listener', 'priority' => 'high']], + 'not a string' => [42], + ]; + + foreach ($cases as $label => $listeners) { + $options = ['transport' => 'sendmail', 'event_listeners' => $listeners]; + $container = $this->containerFor($options, ['listener' => $listener]); + + try { + ($this->subject)($container, 'dot-mail.service.default'); + $this->fail('Expected RuntimeException for ' . $label); + } catch (RuntimeException $e) { + $this->assertStringContainsString('Mail event listener config must be', $e->getMessage(), $label); + } + } + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testListenerConfigWithPriorityIsAttached(): void + { + $listener = new class extends AbstractMailEventListener { + public int $preSend = 0; + + public function onPreSend(MailEvent $e): void + { + $this->preSend++; + } + }; + $options = [ + 'transport' => NullTransport::class, + 'event_listeners' => [['type' => 'listener', 'priority' => 5], 'listener'], + 'message_options' => ['from' => 'from@example.com', 'to' => ['to@example.com']], + ]; + $container = $this->containerFor($options, ['listener' => $listener]); + + $mailService = ($this->subject)($container, 'dot-mail.service.default'); + $mailService->setBody('

Body

'); + $mailService->send(); + + $this->assertSame(2, $listener->preSend); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testGenerateServiceInvalidAdapter(): void + { + $container = $this->containerFor(['transport' => 'test']); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageMatches('/"transport" must be a known alias.*"test" provided/'); + ($this->subject)($container, 'dot-mail.service.default'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testTransportServiceThatIsNotATransportThrows(): void + { + $options = ['transport' => 'not.a.transport']; + $container = $this->containerFor($options, ['not.a.transport' => new MailOptions()]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Provided transport service does not return a'); + ($this->subject)($container, 'dot-mail.service.default'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testGenerateServiceFromMinimalConfiguration(): void + { + $container = $this->containerFor([]); + + $mailService = ($this->subject)($container, 'dot-mail.service.default'); + + $this->assertInstanceOf(MailService::class, $mailService); + $this->assertInstanceOf(SendmailTransport::class, $mailService->getTransport()); + $this->assertNull($mailService->getMessage()->getHtmlBody()); + $this->assertSame([], $mailService->getAttachments()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testGenerateServiceWithBodyContent(): void + { + $options = [ + 'transport' => 'sendmail', + 'message_options' => ['body' => ['content' => '

Hello

', 'charset' => 'iso-8859-1']], + ]; + + $container = $this->containerFor($options); + + $mailService = ($this->subject)($container, 'dot-mail.service.default'); + + $this->assertSame('

Hello

', $mailService->getMessage()->getHtmlBody()); + $this->assertSame('iso-8859-1', $mailService->getMessage()->getHtmlCharset()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testEsmtpTransportWithoutConnectionConfigKeys(): void + { + $options = [ + 'transport' => 'esmtp', + 'smtp_options' => ['host' => 'localhost', 'port' => 587], + ]; + + $container = $this->containerFor($options); + + set_error_handler(static function (int $severity, string $message): never { + throw new ErrorException($message, 0, $severity); + }); + + try { + $transport = ($this->subject)($container, 'dot-mail.service.default')->getTransport(); + } finally { + restore_error_handler(); + } + + $this->assertInstanceOf(EsmtpTransport::class, $transport); + $this->assertSame('', $transport->getUsername()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testEsmtpCredentialsWithSpecialCharacters(): void + { + $options = [ + 'transport' => 'esmtp', + 'smtp_options' => [ + 'host' => 'localhost', + 'port' => 587, + 'connection_config' => ['username' => 'user@example.com', 'password' => 'p:ss/w@rd'], + ], + ]; + + $container = $this->containerFor($options); + + $transport = ($this->subject)($container, 'dot-mail.service.default')->getTransport(); + + $this->assertInstanceOf(EsmtpTransport::class, $transport); + $this->assertSame('user@example.com', $transport->getUsername()); + $this->assertSame('p:ss/w@rd', $transport->getPassword()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testEsmtpTransportConfiguration(): void + { + $options = [ + 'transport' => 'esmtp', + 'smtp_options' => [ + 'host' => 'mail.example.com', + 'port' => 2525, + 'name' => 'client.example.com', + 'connection_time_limit' => 7, + 'connection_config' => ['username' => 'user', 'password' => 'secret'], + ], + ]; + + $transport = ($this->subject)($this->containerFor($options), 'dot-mail.service.default')->getTransport(); + + $this->assertInstanceOf(EsmtpTransport::class, $transport); + $this->assertSame('client.example.com', $transport->getLocalDomain()); + $stream = $transport->getStream(); + $this->assertInstanceOf(SocketStream::class, $stream); + $this->assertSame(7.0, $stream->getTimeout()); + $this->assertTrue($transport->isAutoTls()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testEsmtpTlsSettings(): void + { + $cases = [ + 'automatic on 587' => [587, null, true, false], + 'implicit on 465' => [465, null, true, true], + 'disabled' => [587, false, false, false], + ]; + + foreach ($cases as $label => [$port, $tls, $autoTls, $implicitTls]) { + $options = [ + 'transport' => 'esmtp', + 'smtp_options' => [ + 'host' => 'mail.example.com', + 'port' => $port, + 'connection_config' => ['tls' => $tls], + ], + ]; + + $transport = ($this->subject)($this->containerFor($options), 'dot-mail.service.default')->getTransport(); + + $this->assertInstanceOf(EsmtpTransport::class, $transport); + $this->assertSame($autoTls, $transport->isAutoTls(), $label); + $this->assertInstanceOf(SocketStream::class, $transport->getStream()); + $this->assertSame($implicitTls, $transport->getStream()->isTLS(), $label); + } + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testProvidedTransportObjectIsUsedAsGiven(): void + { + $provided = new EsmtpTransport('provided.example.com', 25, false); + $options = [ + 'transport' => $provided, + 'smtp_options' => ['host' => 'ignored.example.com', 'port' => 587], + ]; + + $transport = ($this->subject)($this->containerFor($options), 'dot-mail.service.default')->getTransport(); + + $this->assertSame($provided, $transport); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testServiceKeepsConfiguredDefaultsAfterReset(): void + { + $options = [ + 'transport' => 'sendmail', + 'message_options' => [ + 'from' => 'from@example.com', + 'subject' => 'Default subject', + 'body' => ['content' => '

Default

'], + 'attachments' => ['files' => ['/some/default/file.txt']], + ], + ]; + + $mailService = ($this->subject)($this->containerFor($options), 'dot-mail.service.default'); + $mailService->getMessage()->addTo('someone@example.com'); + $mailService->addAttachment('/another/file.txt'); + + $mailService->reset(); + + $this->assertSame('Default subject', $mailService->getMessage()->getSubject()); + $this->assertSame('

Default

', $mailService->getMessage()->getHtmlBody()); + $this->assertSame('from@example.com', $mailService->getMessage()->getFrom()[0]->getAddress()); + $this->assertSame([], $mailService->getMessage()->getTo()); + $this->assertSame(['/some/default/file.txt'], $mailService->getAttachments()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testUnconfiguredServiceThrows(): void + { + $container = $this->containerFor(['transport' => 'sendmail']); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Mail service "missing" is not configured under "dot_mail.services"'); + ($this->subject)($container, 'dot-mail.service.missing'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testDefaultServiceIsCreatedWithoutARequestedName(): void + { + $container = $this->containerFor([ + 'transport' => 'sendmail', + 'message_options' => ['from' => 'default@example.com'], + ]); + + $mailService = ($this->subject)($container); + + $this->assertSame('default@example.com', $mailService->getMessage()->getFrom()[0]->getAddress()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testNamedServiceUsesItsOwnConfiguration(): void + { + $container = new InMemoryContainer([ + 'config' => [ + 'dot_mail' => [ + 'services' => [ + 'default' => ['transport' => 'sendmail', 'message_options' => ['from' => 'one@example.com']], + 'newsletter' => ['transport' => 'esmtp', 'message_options' => ['from' => 'news@example.com']], + ], + ], + ], + LogServiceInterface::class => new LogService([]), + ]); + + $newsletter = ($this->subject)($container, 'dot-mail.service.newsletter'); + + $this->assertSame('news@example.com', $newsletter->getMessage()->getFrom()[0]->getAddress()); + $this->assertInstanceOf(EsmtpTransport::class, $newsletter->getTransport()); + } + + /** + * @param array $serviceConfig the dot_mail.services.default configuration + * @param array $services + */ + private function containerFor(array $serviceConfig, array $services = []): ContainerInterface + { + return new InMemoryContainer([ + 'config' => ['dot_mail' => ['services' => ['default' => $serviceConfig]]], + LogServiceInterface::class => new LogService([]), + ] + $services); + } +} diff --git a/test/Fixture/ContainerErrorException.php b/test/Fixture/ContainerErrorException.php new file mode 100644 index 0000000..25576d3 --- /dev/null +++ b/test/Fixture/ContainerErrorException.php @@ -0,0 +1,12 @@ + */ + private array $services = []; + + /** + * @param array $services + */ + public function __construct(array $services = []) + { + foreach ($services as $id => $service) { + $this->set($id, $service); + } + } + + public function set(string $id, mixed $service): void + { + $this->services[$id] = $service; + } + + public function get(string $id): mixed + { + if (! $this->has($id)) { + throw new ServiceNotFoundException(sprintf('Service "%s" was not found', $id)); + } + + $service = $this->services[$id]; + if ($service instanceof Closure) { + try { + $service = $service($this); + } catch (Throwable $e) { + throw new ContainerErrorException(sprintf('Service "%s" could not be created', $id), 0, $e); + } + $this->services[$id] = $service; + } + + return $service; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/Fixture/RecordingTransport.php b/test/Fixture/RecordingTransport.php new file mode 100644 index 0000000..1cb8068 --- /dev/null +++ b/test/Fixture/RecordingTransport.php @@ -0,0 +1,28 @@ + */ + public array $sent = []; + + protected function doSend(SentMessage $message): void + { + $this->sent[] = $message->getOriginalMessage(); + } + + public function __toString(): string + { + return 'recording://'; + } +} diff --git a/test/Fixture/ServiceNotFoundException.php b/test/Fixture/ServiceNotFoundException.php new file mode 100644 index 0000000..403c506 --- /dev/null +++ b/test/Fixture/ServiceNotFoundException.php @@ -0,0 +1,12 @@ +logFile = sys_get_temp_dir() . '/dot-mail-integration-' . uniqid() . '/sent.log'; + $this->transport = new RecordingTransport(); + $this->container = new InMemoryContainer(); + + $dependencies = (new ConfigProvider())()['dependencies']; + foreach ($dependencies['factories'] as $name => $factory) { + $this->registerFactory($name, $factory); + } + foreach ($dependencies['aliases'] as $alias => $target) { + $this->container->set( + $alias, + static fn (ContainerInterface $container): mixed => $container->get($target) + ); + } + + // an application registers every mail service other than "default" itself + $this->registerFactory('dot-mail.service.newsletter', MailServiceFactory::class); + $this->container->set('mail.transport', $this->transport); + $this->container->set('config', [ + 'dot_mail' => [ + 'log' => ['sent' => $this->logFile], + 'services' => [ + 'default' => [ + 'transport' => 'mail.transport', + 'message_options' => ['from' => 'from@example.com'], + ], + 'newsletter' => [ + 'transport' => 'mail.transport', + 'message_options' => ['from' => 'news@example.com'], + ], + ], + ], + ]); + } + + public function tearDown(): void + { + if (is_file($this->logFile)) { + unlink($this->logFile); + } + if (is_dir(dirname($this->logFile))) { + rmdir(dirname($this->logFile)); + } + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testDefaultServiceSendsAndLogs(): void + { + $mailService = $this->container->get(MailServiceInterface::class); + $this->assertInstanceOf(MailServiceInterface::class, $mailService); + $this->assertSame($mailService, $this->container->get('dot-mail.service.default')); + + $mailService->setBody('Email body'); + $mailService->setSubject('Email subject'); + $mailService->getMessage()->addTo('email@example.com', 'User name'); + + $this->assertTrue($mailService->send()->isValid()); + $this->assertCount(1, $this->transport->sent); + $this->assertStringContainsString( + '{"subject":"Email subject","to":["User name "],"cc":[],"bcc":[]}', + (string) file_get_contents($this->logFile) + ); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testNamedServiceIsRegisteredWithTheFactory(): void + { + $newsletter = $this->container->get('dot-mail.service.newsletter'); + $default = $this->container->get('dot-mail.service.default'); + + $this->assertInstanceOf(MailServiceInterface::class, $newsletter); + $this->assertInstanceOf(MailServiceInterface::class, $default); + $this->assertNotSame($default, $newsletter); + $this->assertSame('news@example.com', $newsletter->getMessage()->getFrom()[0]->getAddress()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testDefaultOptionsAreRegistered(): void + { + $options = $this->container->get('dot-mail.options.default'); + + $this->assertInstanceOf(MailOptions::class, $options); + $this->assertSame('from@example.com', $options->getMessageOptions()->getFrom()); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testMimePartBodyIsSent(): void + { + $mailService = $this->container->get(MailServiceInterface::class); + $this->assertInstanceOf(MailServiceInterface::class, $mailService); + + $mailService->getMessage()->addTo('email@example.com'); + $mailService->setBody(new TextPart('plain body')); + + $this->assertTrue($mailService->send()->isValid()); + $this->assertCount(1, $this->transport->sent); + } + + /** + * @param class-string $factory + */ + private function registerFactory(string $name, string $factory): void + { + $this->container->set( + $name, + static function (ContainerInterface $container) use ($factory, $name): object { + $instance = new $factory(); + + return $instance instanceof LogServiceFactory + ? $instance($container) + : $instance($container, $name); + } + ); + } +} diff --git a/test/Options/MailOptionsTest.php b/test/Options/MailOptionsTest.php index ab427c7..e1278bb 100644 --- a/test/Options/MailOptionsTest.php +++ b/test/Options/MailOptionsTest.php @@ -9,6 +9,7 @@ use Dot\Mail\Options\MessageOptions; use Dot\Mail\Options\SmtpOptions; use PHPUnit\Framework\TestCase; +use Symfony\Component\Mailer\Transport\NullTransport; use Symfony\Component\Mailer\Transport\SendmailTransport; use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport; @@ -19,7 +20,7 @@ public function testGettersAndSetters(): void $subject = new MailOptions(); $transport = 'esmtp'; - $transportMap = ['test' => 'array']; + $transportMap = ['null' => [NullTransport::class]]; $messageOptions = ['from' => '', 'to' => []]; $smtpOptions = ['host' => '', 'port' => 587]; $eventListeners = [AbstractMailEventListener::class]; @@ -50,4 +51,14 @@ public function testTransportAliasIsCaseInsensitive(): void $subject->setTransport('Custom\\Transport'); $this->assertSame('Custom\\Transport', $subject->getTransport()); } + + public function testDefaultsWithoutConfiguration(): void + { + $subject = new MailOptions(); + + $this->assertSame(SendmailTransport::class, $subject->getTransport()); + $this->assertContainsOnlyInstancesOf(MessageOptions::class, [$subject->getMessageOptions()]); + $this->assertContainsOnlyInstancesOf(SmtpOptions::class, [$subject->getSmtpOptions()]); + $this->assertSame($subject->getMessageOptions(), $subject->getMessageOptions()); + } } diff --git a/test/Options/MessageOptionsTest.php b/test/Options/MessageOptionsTest.php index 7a68400..42d31a5 100644 --- a/test/Options/MessageOptionsTest.php +++ b/test/Options/MessageOptionsTest.php @@ -48,4 +48,14 @@ public function testGettersAndSetters(): void $this->assertContainsOnlyInstancesOf(BodyOptions::class, [$subject->getBody()]); $this->assertContainsOnlyInstancesOf(AttachmentsOptions::class, [$subject->getAttachments()]); } + + public function testDefaultsWithoutConfiguration(): void + { + $subject = new MessageOptions(); + + $this->assertContainsOnlyInstancesOf(BodyOptions::class, [$subject->getBody()]); + $this->assertSame('', $subject->getBody()->getContent()); + $this->assertContainsOnlyInstancesOf(AttachmentsOptions::class, [$subject->getAttachments()]); + $this->assertSame([], $subject->getAttachments()->getFiles()); + } } diff --git a/test/Options/SmtpOptionsTest.php b/test/Options/SmtpOptionsTest.php index 81cdc08..d24e155 100644 --- a/test/Options/SmtpOptionsTest.php +++ b/test/Options/SmtpOptionsTest.php @@ -41,4 +41,9 @@ public function testPortBoundaries(): void $this->expectExceptionMessage('Port must be greater than 0; received "0"'); $subject->setPort(0); } + + public function testConnectionTimeLimitDefaultsToNull(): void + { + $this->assertNull((new SmtpOptions())->getConnectionTimeLimit()); + } } diff --git a/test/Result/MailResultTest.php b/test/Result/MailResultTest.php index 94c90bf..e5e44b0 100644 --- a/test/Result/MailResultTest.php +++ b/test/Result/MailResultTest.php @@ -7,6 +7,7 @@ use Dot\Mail\Result\MailResult; use Exception; use PHPUnit\Framework\TestCase; +use TypeError; class MailResultTest extends TestCase { @@ -27,4 +28,14 @@ public function testGettersAndSetters(): void $this->assertSame($exception->getMessage(), $mailResult->getException()->getMessage()); $this->assertTrue($mailResult->hasException()); } + + public function testResultCanHoldAnyThrowable(): void + { + $error = new TypeError('Type error test'); + + $mailResult = new MailResult(false, $error->getMessage(), $error); + + $this->assertTrue($mailResult->hasException()); + $this->assertSame($error, $mailResult->getException()); + } } diff --git a/test/Service/LogServiceTest.php b/test/Service/LogServiceTest.php index e2bfe79..74932f4 100644 --- a/test/Service/LogServiceTest.php +++ b/test/Service/LogServiceTest.php @@ -8,7 +8,6 @@ use Dot\Mail\Service\LogService; use DotTest\Mail\CommonTrait; use org\bovigo\vfs\vfsStream; -use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Address; @@ -56,31 +55,39 @@ public function testExtractAddresses(): void ); } - /** - * @throws Exception - */ public function testSentMailIsLogged(): void { - $message = $this->createMock(Email::class); - $toAddress = [new Address('testTo@dotkernel.com')]; - $ccAddress = [new Address('testCc@dotkernel.com')]; - $bccAddress = [new Address('testBcc@dotkernel.com')]; - - $message->expects($this->once())->method('getSubject') - ->willReturn('testSubject@dotkernel.com'); - $message->expects($this->once())->method('getTo') - ->willReturn($toAddress); - $message->expects($this->once())->method('getCc') - ->willReturn($ccAddress); - $message->expects($this->once())->method('getBcc') - ->willReturn($bccAddress); + $message = (new Email())->subject('testSubject@dotkernel.com'); + $message->addTo('testTo@dotkernel.com', 'To Name'); + $message->addCc('testCc@dotkernel.com'); + $message->addBcc('testBcc@dotkernel.com'); $this->logService->sent($message); - $this->assertTrue(is_file($this->config['dot_mail']['log']['sent'])); - $this->assertStringContainsString( - '"subject":"testSubject@dotkernel.com"', - file_get_contents($this->fileSystem->url() . '/log/mail/sent.log') - ); + $logFile = $this->fileSystem->url() . '/log/mail/sent.log'; + $this->assertTrue(is_file($logFile)); + $contents = file_get_contents($logFile); + $this->assertIsString($contents); + $this->assertStringContainsString('"subject":"testSubject@dotkernel.com"', $contents); + $this->assertStringContainsString('"to":["To Name "]', $contents); + $this->assertStringContainsString('"cc":[" "]', $contents); + $this->assertStringContainsString('"bcc":[" "]', $contents); + } + + public function testSentReturnsFalseWhenLogDirectoryCannotBeCreated(): void + { + // the "directory" of the target is an existing file, so it can be neither used nor created + $target = $this->fileSystem->url() . '/data/mail/attachments/testPdfAttachment.pdf/sent.log'; + $logService = new LogService(['log' => ['sent' => $target]]); + $message = new Email(); + + $this->assertFalse($logService->sent($message)); + } + + public function testSentIsDisabledWithoutTarget(): void + { + $logService = new LogService(['log' => ['sent' => null]]); + + $this->assertNull($logService->sent(new Email())); } } diff --git a/test/Service/MailServiceTest.php b/test/Service/MailServiceTest.php index 685711f..53df975 100644 --- a/test/Service/MailServiceTest.php +++ b/test/Service/MailServiceTest.php @@ -5,6 +5,7 @@ namespace DotTest\Mail\Service; use Dot\Mail\Email; +use Dot\Mail\Event\AbstractMailEventListener; use Dot\Mail\Event\MailEvent; use Dot\Mail\Exception\MailException; use Dot\Mail\Exception\RuntimeException; @@ -13,9 +14,10 @@ use Dot\Mail\Service\LogServiceInterface; use Dot\Mail\Service\MailService; use DotTest\Mail\CommonTrait; +use DotTest\Mail\Fixture\RecordingTransport; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Framework\TestCase; use ReflectionClass; use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport; @@ -25,14 +27,20 @@ use Symfony\Component\Mime\Part\DataPart; use Symfony\Component\Mime\Part\Multipart\MixedPart; use Symfony\Component\Mime\Part\TextPart; +use Throwable; +use TypeError; + +use function file_put_contents; +use function mkdir; +use function sort; class MailServiceTest extends TestCase { use CommonTrait; private MailService $mailService; - private Email|MockObject $message; - private TransportInterface|MockObject $transportInterface; + private Email $message; + private TransportInterface&Stub $transportInterface; /** * @throws Exception @@ -40,9 +48,9 @@ class MailServiceTest extends TestCase public function setUp(): void { $this->message = new Email(); - $this->transportInterface = $this->createMock(TransportInterface::class); - $mailOptions = $this->createMock(MailOptions::class); - $logServiceInterface = $this->createMock(LogServiceInterface::class); + $this->transportInterface = $this->createStub(TransportInterface::class); + $mailOptions = new MailOptions(); + $logServiceInterface = $this->createStub(LogServiceInterface::class); $this->mailService = new MailService( $logServiceInterface, @@ -73,7 +81,7 @@ public function setUp(): void public function testGettersAndSetters(): void { $attachments = ['/testAttachment.pdf', '/testDirectory/testAttachment2.xls']; - $transport = $this->createMock(EsmtpTransport::class); + $transport = new EsmtpTransport(); $this->mailService->setAttachments($attachments); $this->mailService->setTransport($transport); @@ -93,6 +101,7 @@ public function testCreateMailEvent(): void $mailEvent = $this->mailService->createMailEvent('testName', $result); $this->assertContainsOnlyInstancesOf(MailEvent::class, [$mailEvent]); $this->assertSame('testName', $mailEvent->getName()); + $this->assertNotNull($mailEvent->getResult()); $this->assertSame(MailResult::DEFAULT_MESSAGE, $mailEvent->getResult()->getMessage()); } @@ -139,9 +148,11 @@ public function testAttachFilesToMimeMessageBody(): void public function testSendFailureTriggersErrorEvent(): void { $exception = new RuntimeException("Test Error Message"); - $this->transportInterface->expects($this->once()) + $transport = $this->createMock(TransportInterface::class); + $transport->expects($this->once()) ->method('send') ->willThrowException($exception); + $this->mailService->setTransport($transport); $this->expectException(MailException::class); $this->expectExceptionMessage("Test Error Message"); @@ -209,23 +220,18 @@ public function testAttachFilesSingleAttachmentIsFlat(): void $this->assertInstanceOf(DataPart::class, $parts[1]); } - public function testAttachFilesSkipsNonExistentFiles(): void + public function testAttachFilesThrowsOnMissingFile(): void { $this->message->html('

Test

'); - $this->mailService->addAttachment('/nonexistent/file.pdf'); $this->mailService->addAttachment( $this->fileSystem->url() . '/data/mail/attachments/testPdfAttachment.pdf' ); + $this->mailService->addAttachment('/nonexistent/file.pdf'); + $this->expectException(MailException::class); + $this->expectExceptionMessage('Attachment "/nonexistent/file.pdf" does not exist or is not readable'); $this->mailService->attachFiles(); - - $body = $this->message->getBody(); - $this->assertInstanceOf(MixedPart::class, $body); - - $parts = $body->getParts(); - // only 1 valid attachment + the html body - $this->assertCount(2, $parts); } public function testAttachFilesPreservesCustomFilename(): void @@ -299,11 +305,10 @@ public function testAttachFilesNoNestedMixedParts(): void /** * Found an attachment leak where DataParts * embedded into Message::$body by attachFiles() survived a failed send - * and were wrapped into the next email. The fix must live in dot-mail: - * after send() (success OR failure) the underlying Message::$body must - * be reset so the next send rebuilds the body from scratch. + * and were wrapped into the next email. After send() (success OR failure) + * the service must hand out a clean message built from the configured defaults. */ - public function testMessageBodyIsResetAfterFailedSendToPreventAttachmentLeak(): void + public function testMessageIsResetAfterFailedSendToPreventAttachmentLeak(): void { $this->mailService->setSubject('First'); $this->message->html('First body'); @@ -322,11 +327,12 @@ public function testMessageBodyIsResetAfterFailedSendToPreventAttachmentLeak(): // expected } + $this->assertNotSame($this->message, $this->mailService->getMessage()); $this->assertNull( - $this->readPrivateMessageBody($this->message), - 'After a failed send the Symfony Message::$body must be reset; ' - . 'otherwise attachFiles() will wrap the leaked MixedPart into the next email.' + $this->readPrivateMessageBody($this->mailService->getMessage()), + 'After a failed send the message must be rebuilt from the defaults, without the attached body.' ); + $this->assertSame([], $this->mailService->getAttachments()); } /** @@ -362,10 +368,9 @@ public function testAttachmentsDoNotLeakIntoSubsequentSendAfterFailure(): void // expected } - // Reconfigure: brand new email with NO attachments. - $this->mailService->setAttachments([]); + // Configure a brand new email; the attachment of the first one must be gone. $this->mailService->setSubject('Second'); - $this->message->html('Second email - must not carry first email\'s attachment'); + $this->mailService->getMessage()->html('Second email - must not carry first email\'s attachment'); $this->mailService->send(); @@ -381,32 +386,309 @@ public function testAttachmentsDoNotLeakIntoSubsequentSendAfterFailure(): void } /** - * Confirms the success path also resets the body, so a future refactor + * Confirms the success path also resets the message, so a future refactor * does not silently regress the success case. */ - public function testMessageBodyIsResetAfterSuccessfulSend(): void + public function testMessageIsResetAfterSuccessfulSend(): void { $this->mailService->setSubject('Hello'); $this->message->html('Body'); + $this->message->addTo('first@example.com'); $this->mailService->addAttachment( $this->fileSystem->url() . '/data/mail/attachments/testPdfAttachment.pdf' ); - $this->transportInterface->expects($this->once())->method('send'); + $transport = $this->createMock(TransportInterface::class); + $transport->expects($this->once())->method('send'); + $this->mailService->setTransport($transport); $this->mailService->send(); - $this->assertNull( - $this->readPrivateMessageBody($this->message), - 'Message body should be null after a successful send so the next email starts clean.' + $message = $this->mailService->getMessage(); + $this->assertNotSame($this->message, $message); + $this->assertNull($this->readPrivateMessageBody($message)); + $this->assertNull($message->getSubject()); + $this->assertSame([], $message->getTo()); + $this->assertSame([], $this->mailService->getAttachments()); + } + + public function testResetRestoresConfiguredDefaults(): void + { + $defaults = new Email(); + $defaults->subject('Default subject'); + $defaults->addFrom('from@example.com'); + + $mailService = new MailService( + $this->createStub(LogServiceInterface::class), + $defaults, + $this->transportInterface, + new MailOptions(), + ['/default/attachment.txt'] ); + + $mailService->setSubject('Changed'); + $mailService->getMessage()->addTo('someone@example.com'); + $mailService->addAttachment('/extra/attachment.txt'); + + $mailService->reset(); + + $this->assertSame('Default subject', $mailService->getMessage()->getSubject()); + $this->assertSame('from@example.com', $mailService->getMessage()->getFrom()[0]->getAddress()); + $this->assertSame([], $mailService->getMessage()->getTo()); + $this->assertSame(['/default/attachment.txt'], $mailService->getAttachments()); + } + + public function testListenersSeeTheFullMessageBeforeTheReset(): void + { + $listener = new class extends AbstractMailEventListener { + /** @var list */ + public array $seen = []; + + public function onPostSend(MailEvent $e): void + { + $this->seen[] = $e->getMailService()->getMessage()->getSubject(); + } + }; + $this->mailService->attachListener($listener); + $this->mailService->setSubject('Visible to listeners'); + + $this->mailService->send(); + + $this->assertSame(['Visible to listeners'], $listener->seen); + $this->assertNull($this->mailService->getMessage()->getSubject()); + } + + public function testSendFailureKeepsThePreviousException(): void + { + $exception = new RuntimeException('Transport failure', 42); + $this->transportInterface->method('send')->willThrowException($exception); + + try { + $this->mailService->send(); + $this->fail('Expected MailException was not thrown'); + } catch (MailException $e) { + $this->assertSame($exception, $e->getPrevious()); + $this->assertSame(42, $e->getCode()); + $this->assertSame('Transport failure', $e->getMessage()); + } + } + + public function testErrorsAreReportedAsSendErrors(): void + { + $listener = new class extends AbstractMailEventListener { + /** @var list */ + public array $events = []; + + public function onSendError(MailEvent $e): void + { + $exception = $e->getResult()?->getException(); + if ($exception !== null) { + $this->events[] = $exception::class; + } + } + }; + $this->mailService->attachListener($listener); + $this->transportInterface->method('send')->willThrowException(new TypeError('Type problem')); + + try { + $this->mailService->send(); + $this->fail('Expected MailException was not thrown'); + } catch (MailException $e) { + $this->assertInstanceOf(TypeError::class, $e->getPrevious()); + } + + $this->assertSame([TypeError::class], $listener->events); + } + + public function testFailingPostSendListenerIsNotReportedAsSendError(): void + { + $listener = new class extends AbstractMailEventListener { + public int $errors = 0; + + public function onPostSend(MailEvent $e): void + { + throw new RuntimeException('Listener failure'); + } + + public function onSendError(MailEvent $e): void + { + $this->errors++; + } + }; + $this->mailService->attachListener($listener); + $this->mailService->setSubject('Delivered'); + + $caught = null; + try { + $this->mailService->send(); + } catch (Throwable $e) { + $caught = $e; + } + + $this->assertInstanceOf(RuntimeException::class, $caught); + $this->assertSame('Listener failure', $caught->getMessage()); + $this->assertSame(0, $listener->errors); + $this->assertNull($this->mailService->getMessage()->getSubject(), 'The message must be reset anyway'); + } + + public function testDirectoryAttachmentsAreCollectedAtSendTime(): void + { + $dir = $this->fileSystem->url() . '/data/mail/attachments'; + file_put_contents($dir . '/.gitkeep', ''); + mkdir($dir . '/nested'); + file_put_contents($dir . '/nested/nested.txt', 'nested'); + + $options = new MailOptions([ + 'message_options' => [ + 'attachments' => ['dir' => ['iterate' => true, 'path' => $dir, 'recursive' => false]], + ], + ]); + + $message = new Email(); + $mailService = new MailService( + $this->createStub(LogServiceInterface::class), + $message, + $this->transportInterface, + $options + ); + $message->html('

Test

'); + + // added after the service was created + file_put_contents($dir . '/late.txt', 'late'); + + $mailService->attachFiles(); + + $body = $message->getBody(); + $this->assertInstanceOf(MixedPart::class, $body); + $names = []; + foreach ($body->getParts() as $part) { + if ($part instanceof DataPart) { + $names[] = $part->getFilename(); + } + } + sort($names); + + $this->assertSame(['late.txt', 'testPdfAttachment.pdf', 'testXlsAttachment.xls'], $names); + } + + public function testRecursiveDirectoryAttachments(): void + { + $dir = $this->fileSystem->url() . '/data/mail/attachments'; + mkdir($dir . '/nested'); + file_put_contents($dir . '/nested/nested.txt', 'nested'); + + $options = new MailOptions([ + 'message_options' => [ + 'attachments' => ['dir' => ['iterate' => true, 'path' => $dir, 'recursive' => true]], + ], + ]); + + $message = new Email(); + $mailService = new MailService( + $this->createStub(LogServiceInterface::class), + $message, + $this->transportInterface, + $options + ); + $message->html('

Test

'); + + $mailService->attachFiles(); + + $body = $message->getBody(); + $this->assertInstanceOf(MixedPart::class, $body); + $this->assertCount(4, $body->getParts()); + } + + public function testHiddenDirectoriesAreNotAttached(): void + { + $dir = $this->fileSystem->url() . '/data/mail/attachments'; + mkdir($dir . '/.git'); + file_put_contents($dir . '/.git/config', 'secret'); + mkdir($dir . '/nested'); + file_put_contents($dir . '/nested/nested.txt', 'nested'); + file_put_contents($dir . '/nested/.env', 'secret'); + + $options = new MailOptions([ + 'message_options' => [ + 'attachments' => ['dir' => ['iterate' => true, 'path' => $dir, 'recursive' => true]], + ], + ]); + + $message = new Email(); + $mailService = new MailService( + $this->createStub(LogServiceInterface::class), + $message, + $this->transportInterface, + $options + ); + $message->html('

Test

'); + + $mailService->attachFiles(); + + $body = $message->getBody(); + $this->assertInstanceOf(MixedPart::class, $body); + $names = []; + foreach ($body->getParts() as $part) { + if ($part instanceof DataPart) { + $names[] = $part->getFilename(); + } + } + sort($names); + + $this->assertSame(['nested.txt', 'testPdfAttachment.pdf', 'testXlsAttachment.xls'], $names); + } + + public function testBodySetAsMimePartIsSent(): void + { + $transport = new RecordingTransport(); + $this->mailService->setTransport($transport); + $this->message->addFrom('from@example.com'); + $this->message->addTo('to@example.com'); + + $this->mailService->setBody(new TextPart('plain body')); + $result = $this->mailService->send(); + + $this->assertTrue($result->isValid()); + $this->assertCount(1, $transport->sent); + $this->assertInstanceOf(Email::class, $transport->sent[0]); + $body = $transport->sent[0]->getBody(); + $this->assertInstanceOf(TextPart::class, $body); + $this->assertSame('plain body', $body->getBody()); + } + + public function testBodySetAsMimePartIsSentWithAttachments(): void + { + $transport = new RecordingTransport(); + $this->mailService->setTransport($transport); + $this->message->addFrom('from@example.com'); + $this->message->addTo('to@example.com'); + + $this->mailService->setBody(new TextPart('plain body')); + $this->mailService->addAttachment($this->fileSystem->url() . '/data/mail/attachments/testPdfAttachment.pdf'); + $this->mailService->send(); + + $this->assertCount(1, $transport->sent); + $this->assertInstanceOf(Email::class, $transport->sent[0]); + $body = $transport->sent[0]->getBody(); + $this->assertInstanceOf(MixedPart::class, $body); + $this->assertCount(2, $body->getParts()); + } + + public function testMessageWithoutAnyBodyIsNotSent(): void + { + $this->message->addFrom('from@example.com'); + $this->message->addTo('to@example.com'); + $this->mailService->setTransport(new RecordingTransport()); + + $this->expectException(MailException::class); + $this->expectExceptionMessage('A message must have a text or an HTML part.'); + $this->mailService->send(); } private function readPrivateMessageBody(Message $message): ?AbstractPart { $reflection = new ReflectionClass(Message::class); $property = $reflection->getProperty('body'); - $property->setAccessible(true); return $property->getValue($message); } @@ -427,4 +709,73 @@ private function bodyContainsDataPart(AbstractPart $part): bool return false; } + + public function testSetBodyUsesProvidedCharset(): void + { + $this->mailService->setBody('

Body

', 'iso-8859-1'); + + $this->assertSame('iso-8859-1', $this->message->getHtmlCharset()); + } + + public function testSetBodyDefaultsToUtf8(): void + { + $this->mailService->setBody('

Body

'); + + $this->assertSame('utf-8', $this->message->getHtmlCharset()); + } + + public function testSendKeepsConfiguredEncoding(): void + { + $encoding = null; + $this->transportInterface->method('send')->willReturnCallback( + function (Email $email) use (&$encoding) { + $encoding = $email->getEncoding(); + return null; + } + ); + + $this->mailService->setBody('

Body

', 'iso-8859-1'); + $this->mailService->send(); + + $this->assertSame('iso-8859-1', $encoding); + } + + public function testSendSetsDefaultEncodingWhenNoneIsSet(): void + { + $encoding = 'not called'; + $this->transportInterface->method('send')->willReturnCallback( + function (Email $email) use (&$encoding) { + $encoding = $email->getEncoding(); + return null; + } + ); + + $this->assertNull($this->message->getEncoding()); + + $this->mailService->send(); + + $this->assertSame('utf-8', $encoding); + } + + /** + * @throws Exception + */ + public function testLogFailureDoesNotBreakSuccessfulSend(): void + { + $logService = $this->createMock(LogServiceInterface::class); + $logService->expects($this->once()) + ->method('sent') + ->willThrowException(new RuntimeException('Log failure')); + + $mailService = new MailService( + $logService, + new Email(), + $this->transportInterface, + new MailOptions() + ); + + $result = $mailService->send(); + + $this->assertTrue($result->isValid()); + } }