diff --git a/_config/base-extensions.yml b/_config/base-extensions.yml index 5733a5d..673a3c2 100755 --- a/_config/base-extensions.yml +++ b/_config/base-extensions.yml @@ -58,6 +58,8 @@ SilverStripe\Core\Injector\Injector: properties: Authenticators: default: '%$A2nt\CMSNiceties\Forms\Authenticator' + SilverStripe\Control\Email\Email: + class: A2nt\CMSNiceties\MailerFix SilverStripe\UserForms\Form\UserForm: extensions: diff --git a/composer.json b/composer.json index fa75613..37ecab8 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,8 @@ "silverstripe/cms": "*", "a2nt/silverstripe-elemental-basics": "*", "silverstripe/widgets": "*", - "gorriecoe/silverstripe-linkfield": "*" + "gorriecoe/silverstripe-linkfield": "*", + "symfony/mailer": "^6" }, "autoload": { "psr-4": { diff --git a/src/MailerFix.php b/src/MailerFix.php new file mode 100644 index 0000000..0fe0d1c --- /dev/null +++ b/src/MailerFix.php @@ -0,0 +1,100 @@ +args = func_get_args(); + parent::__construct($from, $to, $subject, $body, $cc, $bcc, $returnPath); + } + + + private static function convertVars($mails) + { + return is_array($mails) ? implode(' ', $mails) : $mails; + } + + public function send() + { + $transport = Transport::fromDsn('native://default');//smtp://localhost + $mailer = new Mailer($transport); + + $body = $this->getBody(); + $to = self::convertVars($this->args[1]); + + $email = (new MimeEmail()) + ->to($to) + //->priority(Email::PRIORITY_HIGH) + ->subject($this->args[2]) + ->text(strip_tags($body, [])) + ->html($body); + + $from = self::convertVars($this->args[0]); + $from = $from ? $from : self::getDefaultFrom(); + if ($from) { + $email->from($from); + } + + $cc = isset($this->args[4]) ? self::convertVars($this->args[4]) : null; + if ($cc) { + $email->cc($cc); + } + + $bcc = isset($this->args[5]) ? self::convertVars($this->args[5]) : null; + if ($bcc) { + $email->bcc($bcc); + } + + $reply = isset($this->args[6]) ? self::convertVars($this->args[6]) : null; + if ($reply) { + $email->replyTo($reply); + } + + + $mailer->send($email); + //parent::send(); + } + + private function getDefaultFrom(): string + { + // admin_email can have a string or an array config + // https://docs.silverstripe.org/en/4/developer_guides/email/#administrator-emails + $adminEmail =Email::config()->get('admin_email'); + if (is_array($adminEmail) && count($adminEmail ?? []) > 0) { + $defaultFrom = array_keys($adminEmail)[0]; + } else { + if (is_string($adminEmail)) { + $defaultFrom = $adminEmail; + } else { + $defaultFrom = ''; + } + } + if (empty($defaultFrom)) { + $host = Director::host(); + if (empty($host)) { + throw new RuntimeException('Host not defined'); + } + $defaultFrom = sprintf('noreply@%s', $host); + } + + return $defaultFrom; + } +}