postoffice-1.0.x-dev/extensions/postoffice_file/src/EventSubscriber/FileAttachmentSubscriber.php
extensions/postoffice_file/src/EventSubscriber/FileAttachmentSubscriber.php
<?php
namespace Drupal\postoffice_file\EventSubscriber;
use Drupal\postoffice\Email\TemplateAttachmentsInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Email;
/**
* Attaches files supplied by the postoffice_file_X twig filters.
*
* Runs with priority -50 (after Symfony MessageListener which is responsible
* for body rendering).
*/
class FileAttachmentSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[MessageEvent::class] = ['onMessage', -50];
return $events;
}
/**
* Attaches files supplied by the postoffice_file_X twig filters.
*/
public function onMessage(MessageEvent $event): void {
$message = $event->getMessage();
if ($message instanceof Email && $message instanceof TemplateAttachmentsInterface) {
$settings = $message->getTemplateAttachments()->getSettings();
$attachments = $settings['postofficeFileAttachments'] ?? [];
foreach ($attachments as $uri => $attachment) {
['name' => $name, 'mimeType' => $mimeType] = $attachment;
$message->attachFromPath($uri, $name, $mimeType);
}
}
}
}
