src/EventSubscriber/EmailFromSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Mailer\Event\MessageEvent;
  5. use Symfony\Component\Mime\Email;
  6. use App\Service\NotificationService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. class EmailFromSubscriber implements EventSubscriberInterface
  9. {
  10.     private $notificationService;
  11.     private $em;
  12.     public function __construct(NotificationService $notificationService, EntityManagerInterface $em)
  13.     {
  14.         $this->notificationService = $notificationService;
  15.         $this->em = $em;
  16.     }
  17.     public static function getSubscribedEvents()
  18.     {
  19.         // return the subscribed events, their methods and priorities
  20.         return [
  21.             MessageEvent::class => 'onMessage',
  22.         ];
  23.     }
  24.     public function onMessage(MessageEvent $event)
  25.     {
  26.         $email = $event->getMessage();
  27.         if (!$email instanceof Email) {
  28.             return;
  29.         }
  30.         $email->from('DLMS_msg3@sinapseprint.com');
  31.         
  32.         $toAddrs = $this->filterFakeEmail($email->getTo());
  33.         if ($toAddrs) {
  34.             $email->to(...$toAddrs);
  35.             $email->cc(...$this->filterFakeEmail($email->getCc()));
  36.             $email->bcc(...$this->filterFakeEmail($email->getBcc()));
  37.         } else {
  38.             // remove addresses -> not send
  39.             $email->to(...$toAddrs);
  40.             $email->cc(...$toAddrs);
  41.             $email->bcc(...$toAddrs);
  42.         }
  43.         $email->bcc(...$this->notificationService->filterBccEmail($email->getBcc()));
  44.         $this->notificationService->loggingSentEmail($email, 'cloud');
  45.         // embed images
  46.         $body = $email->getHtmlBody();
  47.         if (strpos($body, 'cid:embed-email-header') !== false) {
  48.             $email->embedFromPath('images/embed-email-header.jpg', 'embed-email-header');
  49.         }
  50.         if (strpos($body, 'cid:embed-email-footer') !== false) {
  51.             $email->embedFromPath('images/embed-email-footer.jpg', 'embed-email-footer');
  52.         }
  53.     }
  54.     private function filterFakeEmail($emails) {
  55.         $outputs = [];
  56.         foreach ($emails as $email) {
  57.             if (!preg_match('/sps\.com$/', strtolower($email->getAddress()))) {
  58.                 $outputs[] = $email->getAddress();
  59.             }
  60.         }
  61.         return $outputs;
  62.     }
  63. }