2

I am using hook_mail_alter in drupal 8 to alter the email messages sent through contact form . How can I access $message['params'] fields in hook_mail_alter()?

I am getting the following values with print_r(array_keys($message['params']));.

Array (
  [0] => contact_message
  [1] => sender
  [2] => contact_form
)

Can anyone suggest how I access the contact form fields?

When I access the values with print_r($message['params']['contact_form']);die; I don't get anything displayed.

2 Answers 2

4

The message entity is stored in $message['params']['contact_message'] and it contains all the values from the contact form. Given that it's an entity of type contact_message, you can operate with get() method to get the values of any field that your contact message might have. Example:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {
  if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];
    // Get sender's name.
    $sender_name = $contact_message->getSenderName();
    // Get sender's mail.
    $sender_mail = $contact_message->getSenderMail();
    // Get subject.
    $subject = $contact_message->getSubject();
    // Get message.
    $message_body = $contact_message->getMessage();
    // Get the value of "field_request" field.
    $request_value = $contact_message->get('field_request')->getValue();
  }
}
0

The original post assumes the use of the "Contact" module, but for a more generic solution (for example, for user account registration/activation emails), you can access user account information via the 'account' element:

/**
 * Implements hook_mail_alter().
 *
 * Modify outgoing emails.
 */
function mymodule_mail_alter(&$message) {
  switch ($message['id']) {
    case 'user_register_pending_approval':
      $field_data = $message['params']['account']->get('field_example')->getValue();
      // do something with $field_data in $message['body']
      break;

    case 'user_status_activated':
      if ($message['params']['account']->hasRole('content_editor')) {
        // do something with $field_data in $message['body']
      }
      break;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.