Drupal 9: Simplenews, Swiftmailer and Attachments (via hook_mail_alter)

Posted by kelly on Tue, 08/30/2022 - 21:16

In Drupal 8/9 simplenews can add attachments only from file-field (and I am not sure if this works correctly because simplenews is adding the whole file-entity to the attachments-array and swiftmailer awaits a special array).

To handle your own attachments e.g. in referenced media-entities you can use hook_mail_alter().

In this example the attached files come from the media-entities stored in "field_upload_media":

/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
 
  // Add Attachments from field_upload_media to simplenews.
  if (isset($message['params']['simplenews_mail'])) {
 
    // Get simplenews-mail-object.
    $mail = $message['params']['simplenews_mail'];
 
    // Get newsletter-node from mail-object.
    $node = $mail->getIssue();
 
    // Get all referenced media entities from field_upload_media.
    if ($items = $node->get('field_upload_media')->referencedEntities()) {
 
      $attachments = [];
      foreach ($items as $item) {
 
        // Get file entity from field_media_file.
        $file = $item->get('field_media_file')->entity;
 
        // Get mime-type.
        $filemime = $file->getMimeType();
 
        // Get file-uri and realpath.
        $uri = $file->getFileUri();
        $filepath = \Drupal::service('file_system')->realpath($uri);
 
        // Build array for swiftailer and add to message.
        $attachments[] = [
          'filepath' => $filepath,
          'filename' => basename($filepath),
          'filemime' => $filemime,
        ];
      }
      $message['params']['attachments'] = $attachments;
    }
  }
}

 

Systems
Drupal 8/9