You are here

function mimemail_rules_action_mail_to_users_of_role in Mime Mail 6

Implements action to send mail to all users of a specific role group(s).

File

includes/mimemail.rules.inc, line 92
Rules actions for sending MIME-encoded e-mails.

Code

function mimemail_rules_action_mail_to_users_of_role($settings) {
  $key = !empty($settings['key']) ? $settings['key'] : 'rules_action_role_mail';
  $recipients = array_filter(array_keys(array_filter($settings['recipients'])));

  // All authenticated users, which is everybody.
  if (in_array(DRUPAL_AUTHENTICATED_RID, $recipients)) {
    $result = db_query('SELECT mail FROM {users} WHERE uid > 0');
  }
  else {
    $rids = implode(',', $recipients);

    // Avoid sending emails to members of two or more target role groups.
    $result = db_query('SELECT DISTINCT u.mail FROM {users} u INNER JOIN {users_roles} r ON u.uid = r.uid WHERE r.rid IN (' . $rids . ')');
  }

  // Set the sender name and from address.
  if (empty($settings['from'])) {
    $from = NULL;
  }
  else {
    $from = array(
      'name' => $settings['sender'],
      'mail' => $settings['from'],
    );
  }
  while ($account = db_fetch_object($result)) {

    // Prepare the message but don't send.
    $message = drupal_mail('mimemail', $key, $account->mail, user_preferred_language($account), $settings, $from, FALSE);

    // Send the prepared message.
    $message = mimemail($message['from'], $message['to'], $message['subject'], $message['body'], NULL, $message['headers'], $message['params']['plaintext'], $message['params']['attachments'], $message['id']);
  }
  if ($message['result']) {
    $roles = array_intersect_key(user_roles(TRUE), drupal_map_assoc($recipients));
    watchdog('rules', 'HTML mail successfully sent to role(s) %roles.', array(
      '%roles' => implode(', ', $roles),
    ));
  }
}