Skip to content

Commit

Permalink
Merge branch '4.10' into 4
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Mar 7, 2022
2 parents f666537 + 59800b5 commit 09fdfc4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/Control/Email/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace SilverStripe\Control\Email;

use DateTime;
use RuntimeException;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
use SilverStripe\Control\Director;
Expand All @@ -25,7 +26,6 @@
*/
class Email extends ViewableData
{

/**
* @var array
* @config
Expand Down Expand Up @@ -276,14 +276,30 @@ public function setSwiftMessage($swiftMessage)
$dateTime = new DateTime();
$dateTime->setTimestamp(DBDatetime::now()->getTimestamp());
$swiftMessage->setDate($dateTime);
if (!$swiftMessage->getFrom() && ($defaultFrom = $this->config()->get('admin_email'))) {
$swiftMessage->setFrom($defaultFrom);
if (!$swiftMessage->getFrom()) {
$swiftMessage->setFrom($this->getDefaultFrom());
}
$this->swiftMessage = $swiftMessage;

return $this;
}

/**
* @return string
*/
private function getDefaultFrom(): string
{
$defaultFrom = $this->config()->get('admin_email');
if (!$defaultFrom) {
$host = Director::host();
if (empty($host)) {
throw new RuntimeException('Host not defined');
}
$defaultFrom = sprintf('no-reply@%s', $host);
}
return $defaultFrom;
}

/**
* @return string[]
*/
Expand Down
22 changes: 22 additions & 0 deletions tests/php/Control/Email/EmailTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use DateTime;
use PHPUnit\Framework\MockObject\MockObject;
use SilverStripe\Control\Director;
use SilverStripe\Control\Email\Email;
use SilverStripe\Control\Email\Mailer;
use SilverStripe\Control\Email\SwiftMailer;
Expand All @@ -24,6 +25,12 @@
class EmailTest extends SapphireTest
{

protected function setUp()
{
parent::setUp();
Director::config()->set('alternate_base_url', 'http://www.mysite.com/');
}

public function testAddAttachment()
{
$email = new Email();
Expand Down Expand Up @@ -662,6 +669,21 @@ public function testMultipleEmailSends()
$this->assertStringContainsString('Test', $plainPart->getBody());
}

public function testGetDefaultFrom()
{
$email = new Email();
$class = new \ReflectionClass(Email::class);
$method = $class->getMethod('getDefaultFrom');
$method->setAccessible(true);

// default to [email protected] if admin_email config not set
$this->assertSame('[email protected]', $method->invokeArgs($email, []));

// use admin_email config
Email::config()->set('admin_email', '[email protected]');
$this->assertSame('[email protected]', $method->invokeArgs($email, []));
}

/**
* @return MockObject|Email
*/
Expand Down

0 comments on commit 09fdfc4

Please sign in to comment.