function SystemEmailToUsersOfRole::doExecute

Sends an email to all users of the specified role(s).

Parameters

\Drupal\user\RoleInterface[] $roles: Array of user roles.

string $subject: Subject of the email.

string $message: Email message text.

string $reply: (optional) Reply to email address.

\Drupal\Core\Language\LanguageInterface $language: (optional) Language object. If not specified, email will be sent to each recipient in the recipient's preferred language.

File

src/Plugin/RulesAction/SystemEmailToUsersOfRole.php, line 122

Class

SystemEmailToUsersOfRole
Provides a 'Email to users of a role' action.

Namespace

Drupal\rules\Plugin\RulesAction

Code

protected function doExecute(array $roles, $subject, $message, $reply = NULL, LanguageInterface $language = NULL) {
    if (empty($roles)) {
        return;
    }
    $rids = array_map(function ($role) {
        return $role->id();
    }, $roles);
    // Set a unique key for this email.
    $key = 'rules_action_mail_' . $this->getPluginId();
    // Select only active users, based on the roles given. We do not want to
    // send email to blocked users.
    $accounts = $this->userStorage
        ->loadByProperties([
        'roles' => $rids,
        'status' => 1,
    ]);
    $params = [
        'subject' => $subject,
        'message' => $message,
    ];
    // Loop over users and send email to each individually using that user's
    // preferred language (or a fixed language, if passed in the context).
    $number = 0;
    foreach ($accounts as $account) {
        // Language to use. Value passed in the context takes precedence.
        // ORIG.
        $langcode = isset($language) ? $language->getId() : $account->getPreferredLangcode();
        // @todo Is this better?
        $langcode = isset($language) && $language->getId() != LanguageInterface::LANGCODE_NOT_SPECIFIED ? $language->getId() : $account->getPreferredLangcode();
        $message = $this->mailManager
            ->mail('rules', $key, $account->getEmail(), $langcode, $params, NULL);
        $number += $message['result'] ? 1 : 0;
    }
    $this->logger
        ->notice('Successfully sent email to %number out of %count users having the role(s) %roles', [
        '%number' => $number,
        '%count' => count($accounts),
        '%roles' => implode(', ', $rids),
    ]);
}