<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Email;
use App\Service\NotificationService;
use Doctrine\ORM\EntityManagerInterface;
class EmailFromSubscriber implements EventSubscriberInterface
{
private $notificationService;
private $em;
public function __construct(NotificationService $notificationService, EntityManagerInterface $em)
{
$this->notificationService = $notificationService;
$this->em = $em;
}
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
MessageEvent::class => 'onMessage',
];
}
public function onMessage(MessageEvent $event)
{
$email = $event->getMessage();
if (!$email instanceof Email) {
return;
}
$email->from('DLMS_msg3@sinapseprint.com');
$toAddrs = $this->filterFakeEmail($email->getTo());
if ($toAddrs) {
$email->to(...$toAddrs);
$email->cc(...$this->filterFakeEmail($email->getCc()));
$email->bcc(...$this->filterFakeEmail($email->getBcc()));
} else {
// remove addresses -> not send
$email->to(...$toAddrs);
$email->cc(...$toAddrs);
$email->bcc(...$toAddrs);
}
$email->bcc(...$this->notificationService->filterBccEmail($email->getBcc()));
$this->notificationService->loggingSentEmail($email, 'cloud');
// embed images
$body = $email->getHtmlBody();
if (strpos($body, 'cid:embed-email-header') !== false) {
$email->embedFromPath('images/embed-email-header.jpg', 'embed-email-header');
}
if (strpos($body, 'cid:embed-email-footer') !== false) {
$email->embedFromPath('images/embed-email-footer.jpg', 'embed-email-footer');
}
}
private function filterFakeEmail($emails) {
$outputs = [];
foreach ($emails as $email) {
if (!preg_match('/sps\.com$/', strtolower($email->getAddress()))) {
$outputs[] = $email->getAddress();
}
}
return $outputs;
}
}