I am using the following code that programmatically creates a file and attaches it to a file field when a contact form is submitted.

function mymodule_form_alter(&$form, &$form_state, $form_id) {          
  $form['actions']['submit']['#submit'][] = 'custom_submit_handler';

function custom_submit_handler(&$form, &$form_state) {
  $file_contents = '777';  
  $filename = 'my_file.txt';
  $file = File::create([
    'uri' => 'public://' . $filename,
    'filename' => $filename,

  file_put_contents($file->getFileUri(), $file_contents);
  $entity = $form_state->getFormObject()->getEntity();

The code works as expected, but there is no link to the new file in the sent email.

What should I do to change the email message?

2 Answers 2


The solution is to use hook_entity_presave() instead of hook_form_alter()

function mymodule_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'contact_message') {
    //create and save file
    $entity->set('my_field_file', $file);

In order to enhance the content of our outgoing emails, I strongly recommend utilizing the hook_mail_alter function. This function allows us to modify the email content dynamically just before it is sent. By leveraging this feature, we can personalize and optimize our messages to better engage our recipients.

To learn more about hook_mail_alter and how to implement it effectively, I encourage you to visit the following link: hook_mail_alter.

The provided documentation will guide you through the process of using hook_mail_alter to tailor the content of our emails to suit specific scenarios and recipients. It's a powerful tool that can help us improve the effectiveness of our communication efforts.

 function hook_mail_alter(&$message) {
   if ($message['id'] == 'modulename_messagekey') {
    if (!example_notifications_optin($message['to'], $message['id'])) {

     // If the recipient has opted to not receive such messages, cancel
     // sending.
     $message['send'] = FALSE;
   $message['body'][] = "--\nMail sent out from " . \Drupal::config('system.site')
  • The question is about the contact_message entity and a field in that entity that needs to be changed. hook_mail_alter() does not allow to change that entity. Furthermore, an answer should be tailored for the asked question. Providing a generic hook implementation does not answer the question.
    – apaderno
    Jun 12 at 12:37

Your Answer

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

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