class MailHandler

Same name in other branches
  1. 8.9.x core/modules/contact/src/MailHandler.php \Drupal\contact\MailHandler
  2. 10 core/modules/contact/src/MailHandler.php \Drupal\contact\MailHandler
  3. 11.x core/modules/contact/src/MailHandler.php \Drupal\contact\MailHandler

Provides a class for handling assembly and dispatch of contact mail messages.

Hierarchy

Expanded class hierarchy of MailHandler

1 file declares its use of MailHandler
MailHandlerTest.php in core/modules/contact/tests/src/Unit/MailHandlerTest.php
1 string reference to 'MailHandler'
contact.services.yml in core/modules/contact/contact.services.yml
core/modules/contact/contact.services.yml
1 service uses MailHandler
contact.mail_handler in core/modules/contact/contact.services.yml
Drupal\contact\MailHandler

File

core/modules/contact/src/MailHandler.php, line 16

Namespace

Drupal\contact
View source
class MailHandler implements MailHandlerInterface {
    use StringTranslationTrait;
    
    /**
     * Language manager service.
     *
     * @var \Drupal\Core\Language\LanguageManagerInterface
     */
    protected $languageManager;
    
    /**
     * Logger service.
     *
     * @var \Drupal\Core\Logger\LoggerChannelInterface
     */
    protected $logger;
    
    /**
     * Mail manager service.
     *
     * @var \Drupal\Core\Mail\MailManagerInterface
     */
    protected $mailManager;
    
    /**
     * The user entity storage handler.
     *
     * @var \Drupal\Core\Entity\EntityStorageInterface
     */
    protected $userStorage;
    
    /**
     * Constructs a new \Drupal\contact\MailHandler object.
     *
     * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
     *   Mail manager service.
     * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
     *   Language manager service.
     * @param \Psr\Log\LoggerInterface $logger
     *   A logger instance.
     * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
     *   String translation service.
     * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
     *   The entity type manager.
     */
    public function __construct(MailManagerInterface $mail_manager, LanguageManagerInterface $language_manager, LoggerInterface $logger, TranslationInterface $string_translation, EntityTypeManagerInterface $entity_type_manager) {
        $this->languageManager = $language_manager;
        $this->mailManager = $mail_manager;
        $this->logger = $logger;
        $this->stringTranslation = $string_translation;
        $this->userStorage = $entity_type_manager->getStorage('user');
    }
    
    /**
     * {@inheritdoc}
     */
    public function sendMailMessages(MessageInterface $message, AccountInterface $sender) {
        // Clone the sender, as we make changes to mail and name properties.
        $sender_cloned = clone $this->userStorage
            ->load($sender->id());
        $params = [];
        $current_langcode = $this->languageManager
            ->getCurrentLanguage()
            ->getId();
        $recipient_langcode = $this->languageManager
            ->getDefaultLanguage()
            ->getId();
        $contact_form = $message->getContactForm();
        if ($sender_cloned->isAnonymous()) {
            // At this point, $sender contains an anonymous user, so we need to take
            // over the submitted form values.
            $sender_cloned->name = $message->getSenderName();
            $sender_cloned->mail = $message->getSenderMail();
            // For the email message, clarify that the sender name is not verified; it
            // could potentially clash with a username on this site.
            $sender_cloned->name = $this->t('@name (not verified)', [
                '@name' => $message->getSenderName(),
            ]);
        }
        // Build email parameters.
        $params['contact_message'] = $message;
        $params['sender'] = $sender_cloned;
        if (!$message->isPersonal()) {
            // Send to the form recipient(s), using the site's default language.
            $params['contact_form'] = $contact_form;
            $to = implode(', ', $contact_form->getRecipients());
        }
        elseif ($recipient = $message->getPersonalRecipient()) {
            // Send to the user in the user's preferred language.
            $to = $recipient->getEmail();
            $recipient_langcode = $recipient->getPreferredLangcode();
            $params['recipient'] = $recipient;
        }
        else {
            throw new MailHandlerException('Unable to determine message recipient');
        }
        // Send email to the recipient(s).
        $key_prefix = $message->isPersonal() ? 'user' : 'page';
        $this->mailManager
            ->mail('contact', $key_prefix . '_mail', $to, $recipient_langcode, $params, $sender_cloned->getEmail());
        // If requested, send a copy to the user, using the current language.
        if ($message->copySender()) {
            $this->mailManager
                ->mail('contact', $key_prefix . '_copy', $sender_cloned->getEmail(), $current_langcode, $params, $sender_cloned->getEmail());
        }
        // If configured, send an auto-reply, using the current language.
        if (!$message->isPersonal() && $contact_form->getReply()) {
            // User contact forms do not support an auto-reply message, so this
            // message always originates from the site.
            if (!$sender_cloned->getEmail()) {
                $this->logger
                    ->error('Error sending auto-reply, missing sender e-mail address in %contact_form', [
                    '%contact_form' => $contact_form->label(),
                ]);
            }
            else {
                $this->mailManager
                    ->mail('contact', 'page_autoreply', $sender_cloned->getEmail(), $current_langcode, $params);
            }
        }
        if (!$message->isPersonal()) {
            $this->logger
                ->notice('%sender-name (@sender-from) sent an email regarding %contact_form.', [
                '%sender-name' => $sender_cloned->getAccountName(),
                '@sender-from' => $sender_cloned->getEmail() ?? '',
                '%contact_form' => $contact_form->label(),
            ]);
        }
        else {
            $this->logger
                ->notice('%sender-name (@sender-from) sent %recipient-name an email.', [
                '%sender-name' => $sender_cloned->getAccountName(),
                '@sender-from' => $sender_cloned->getEmail(),
                '%recipient-name' => $message->getPersonalRecipient()
                    ->getAccountName(),
            ]);
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
MailHandler::$languageManager protected property Language manager service.
MailHandler::$logger protected property Logger service.
MailHandler::$mailManager protected property Mail manager service.
MailHandler::$userStorage protected property The user entity storage handler.
MailHandler::sendMailMessages public function Sends mail messages as appropriate for a given Message form submission. Overrides MailHandlerInterface::sendMailMessages
MailHandler::__construct public function Constructs a new \Drupal\contact\MailHandler object.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.