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.


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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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