postoffice-1.0.x-dev/src/EventSubscriber/DefaultAddressSubscriber.php
src/EventSubscriber/DefaultAddressSubscriber.php
<?php
namespace Drupal\postoffice\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
/**
* Message subscriber which sets the site email as the default address.
*
* Runs with priority -200 (after Symfony MessageListener which is
* responsible for body rendering).
*/
class DefaultAddressSubscriber implements EventSubscriberInterface {
/**
* The config factory.
*/
protected ConfigFactoryInterface $configFactory;
/**
* Constructs a new default address subscriber.
*/
public function __construct(ConfigFactoryInterface $configFactory) {
$this->configFactory = $configFactory;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[MessageEvent::class] = ['onMessage', -200];
return $events;
}
/**
* Generate a text fallback if possible.
*/
public function onMessage(MessageEvent $event): void {
$message = $event->getMessage();
$envelope = $event->getEnvelope();
if ($message instanceof Email) {
if (empty($message->getSender())) {
$message->sender($this->getDefaultSender());
}
if (empty($envelope->getSender())) {
$envelope->setSender($message->getSender());
}
if (empty($message->getFrom())) {
$message->from($this->getDefaultFrom());
}
if (empty($message->getTo())) {
$message->to($this->getDefaultTo());
}
}
}
/**
* Get default sender address.
*/
protected function getDefaultSender(): Address {
return $this->getSiteAddress();
}
/**
* Get default from address.
*/
protected function getDefaultFrom(): Address {
return $this->getSiteAddress();
}
/**
* Get default to address.
*/
protected function getDefaultTo(): Address {
return $this->getSiteAddress();
}
/**
* Determine site email.
*/
protected function getSiteAddress(): Address {
$config = $this->configFactory->get('system.site');
// Get the custom site notification email to use as the from email address
// if it has been set.
$siteMail = $config->get('mail_notification');
// If the custom site notification email has not been set, we use the site
// default for this.
if (empty($siteMail)) {
$siteMail = $config->get('mail');
}
if (empty($siteMail)) {
$siteMail = ini_get('sendmail_from');
}
return new Address($siteMail, $config->get('name'));
}
}
