Question

How to stop default mail , i want to override default mail with my custom body message?

Here is my code :

function mag_api_mail_alter(&$message) {
  // only alter register forms
  if (!empty($message['id']) && $message['id'] == 'user_register_no_approval_required') {

  // make it a bit neater to access fields
    
    $nids = \Drupal::entityQuery('node')->condition('type','email_template')->execute();
    $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
    $data_fields = array();
    foreach ($nodes as $new_data){
        $data_fields[] = $new_data->get('body')->getValue();
    }
    $contact_message = $message['params']['account'];
    $first_name = $contact_message->field_first_name->value;
    $username_email = $contact_message->get('name')->value;
    $pass = 'test';
    $app_url = 'abcd.com';
    
    /*custom field added through configuration*/
    
    $to_replace_keys = array("[user_name]","[user_email]","[user_password]","[app_url]");
    $replace_keys =array($first_name,$username_email,$pass,$app_url);
    $success_email_msg = str_replace($to_replace_keys, $replace_keys,$data_fields[0][0]['value']);
    // Assigning new message to mail body.
    $message['body'][] = $success_email_msg;
    
   }
}

Its is working but i am not able to find out why is this showing default mail message as well new body message.

I just want to show my custom body message.

Was it helpful?

Solution

$message['body'][] = $success_email_msg; is appending your variable to the existing array. You'll need to remove the default content from the $message['body'] array if you don't want it

e.g. unset($message['body']['whateverkey']) to remove a specific part. Or $message['body'] = [$success_email_msg]; to reinitialise the variable as a new array

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top