Loading src/UnicaenMail/Service/Mail/MailService.php +167 −98 Original line number Diff line number Diff line Loading @@ -8,28 +8,51 @@ use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\QueryBuilder; use DoctrineModule\Persistence\ProvidesObjectManager; use Exception; use RuntimeException; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Mime\Email; use UnicaenMail\Entity\Db\Mail; use Laminas\Mail\Message; use Laminas\Mime\Message as MimeMessage; use Laminas\Mime\Mime; use Laminas\Mime\Part; use Laminas\Mvc\Controller\AbstractActionController; use RuntimeException; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Mime\Email; use UnicaenMail\Entity\Db\Mail; use UnicaenMail\Exception\NotFoundConfigException; class MailService { class MailService { use ProvidesObjectManager; const BODY_TEXT_TEMPLATE = <<<EOS ----------------------------------------------------------------------- Ce mail a été redirigé. Destinataires originaux : To: %s Cc: %s Bcc: %s EOS; const BODY_HTML_TEMPLATE = <<<EOS <p>Ce mail a été redirigé.</p> <p> Destinataires originaux :<br /> To: %s<br /> Cc: %s<br /> Bcc: %s </p> EOS; private ?Mailer $mailer; public function getMailer(): ?Mailer { return $this->mailer; } public function setMailer(?Mailer $mailer): void { $this->mailer = $mailer; Loading @@ -39,6 +62,7 @@ class MailService { private ?string $entityClass = null; private array $config = []; /** * @param string $entityClass * @return MailService Loading @@ -49,17 +73,20 @@ class MailService { return $this; } public function setConfig(array $config): void { $this->config = $config; } public function createMailEntity() : Object public function createMailEntity(): object { $entity = new $this->entityClass(); return $entity; } /** GESTION DES ENTITES *******************************************************************************************/ public function create(Mail $mail): Mail Loading @@ -69,12 +96,14 @@ class MailService { return $mail; } public function update(Mail $mail): Mail { $this->objectManager->flush($mail); return $mail; } public function delete(Mail $mail): Mail { $this->objectManager->remove($mail); Loading @@ -82,6 +111,7 @@ class MailService { return $mail; } /** REQUETAGE *****************************************************************************************************/ public function createQueryBuilder(): QueryBuilder Loading @@ -90,6 +120,7 @@ class MailService { return $qb; } /** * @param string $champ * @param string $ordre Loading @@ -104,6 +135,7 @@ class MailService { return $result; } public function getMailsByMotClef(string $motClef, string $champ = 'dateEnvoi', string $ordre = 'DESC'): array { // todo ici un fix sal au probleme de MotClef1 === MotClef123 avec MotClef1 inclu dans MotClef123 Loading @@ -116,6 +148,7 @@ class MailService { return $result; } public function getMail(?int $id): ?Mail { $qb = $this->createQueryBuilder() Loading @@ -129,6 +162,7 @@ class MailService { return $result; } public function getRequestedMail(AbstractActionController $controller, string $param = 'mail'): ?Mail { $id = $controller->params()->fromRoute($param); Loading @@ -154,62 +188,31 @@ class MailService { return $value; } /** Transforme un mail Unicaen en Mail Symfony */ public function transform(Mail $mail, ?string $module = null): Email { try { $fromEmail = $this->fetchValueFromConfig('from_email', $module); $fromName = $this->fetchValueFromConfig('from_name', $module); $subjectPrefix = $this->fetchValueFromConfig('subject_prefix', $module); $redirect = $this->fetchValueFromConfig('redirect', $module); $redirectTo = $this->fetchValueFromConfig('redirect_to', $module); } catch (NotFoundConfigException $e) { throw new RuntimeException("Un problème est survenu lors de la récupération de valeurs de config", 0, $e); } $to = (is_string($mail->getDestinataires()))?explode(',',$mail->getDestinataires()):[]; $co = (is_string($mail->getCopies()))?explode(',',$mail->getCopies()):[]; $sujet = "[".$subjectPrefix. "] ".$mail->getSujet(); $corps = "<p><i>Ce courrier électronique vous a été adressé <strong>automatiquement</strong> par l'application ".$subjectPrefix.". </i></p>" . $mail->getCorps(); if ($redirect) { $to = $redirectTo; $sujet .= " {REDIR}"; $corps .= "<br/><br/><hr/><br/>"; $corps .= "Initialement envoyé à :"; $corps .= "<ul>"; foreach (explode(",",$mail->getDestinatairesInitials()) as $t) $corps .= "<li>" . $t . "</li>"; $corps .= "</ul>"; if ($mail->getCopies() !== null && !empty($co)) { $corps .= "Copie à :"; $corps .= "<ul>"; foreach ($co as $e) $corps .= "<li>".$e."</li>"; $corps .= "</ul>"; } } $message = (new Email()) ->from("'\"".$fromName."\" <".$fromEmail.">'") ->subject($sujet) ->text(strip_tags($corps)) ->html($corps); $message->to(...$to); $attachments = ($mail->getAttachmentPaths())?explode("#<>#",$mail->getAttachmentPaths()):[]; foreach ($attachments as $path) { $basename = basename($path); $extension = (explode('.', $basename)[1])??'bin'; $message->attachFromPath($path, $basename, 'application/' . $extension); } if (!$redirect) { if ($co !== null and !empty($co) and $co !== ['']) $message->cc(...$co); $mailSymfony = new Email(); $mailSymfony->from("'\"" . $fromName . "\" <" . $fromEmail . ">'"); $adresseToArray = $redirect ? explode(',', $mail->getDestinatairesInitials()) : (explode(',', $mail->getDestinataires())); $mailSymfony->to(...$adresseToArray); if ($mail->getCopies() !== null) { $adresseCcArray = explode(',', $mail->getCopies()); $mailSymfony->cc(...$adresseCcArray); } $mailSymfony->subject($mail->getSujet()); $mailSymfony->html($mail->getCorps()); $mailSymfony->text(strip_tags($mail->getCorps())); //if ($mail->getCopies()) $message = $message->bcc($mail->getCopies()); return $message; return $mailSymfony; } public function sendMail($to, $subject, $texte, ?string $module = null, $attachement_path = null, $copie = null): ?Mail Loading @@ -218,47 +221,44 @@ class MailService { $doNotSend = $this->fetchValueFromConfig('do_not_send', $module); $redirect = $this->fetchValueFromConfig('redirect', $module); $redirectTo = $this->fetchValueFromConfig('redirect_to', $module); $subjectPrefix = $this->fetchValueFromConfig('subject_prefix', $module); } catch (NotFoundConfigException $e) { throw new RuntimeException("Un problème est survenu lors de la récupération de valeurs de config", 0, $e); } if ($to=== null OR $to === "" OR $to === []) { if ($to === null or $to === "" or $to === []) { return null; } if (is_string($to)) $to=explode(',', $to); if (!is_array($to)) $to = [$to]; if (is_string($copie)) $copie=explode(',', $copie); if (!is_array($copie)) $copie = [$copie]; /** @var Mail $mail */ $mail = $this->createMailEntity(); $mail->setDateEnvoi(new DateTime()); $mail->setStatusEnvoi(Mail::PENDING); $mail->setDestinataires(is_array($to) ? implode(",", $to) : $to); if ($redirect) { $mail->setDestinatairesInitials(implode(",",$to)); $mail->setDestinataires(implode(",", $redirectTo)); $mail->setDestinatairesInitials($to); $mail->setDestinataires(implode(',',$redirectTo)); } else { $mail->setDestinataires(implode(",",$to)); $mail->setDestinataires($to); } if ($copie !== null and !empty($copie)) $mail->setCopies(implode(",", $copie)); $mail->setSujet($subject); $mail->setCorps($texte); if ($copie !== null and !empty($copie)) $mail->setCopies($copie); $sujet = "[" . $subjectPrefix . "] " . $subject; $mail->setSujet($sujet); $corps = "<p><i>Ce courrier électronique vous a été adressé <strong>automatiquement</strong> par l'application " . $subjectPrefix . ". </i></p>" . $texte; $mail->setCorps($corps); if ($attachement_path !== null) { $attachement_path = (is_string($attachement_path)) ? $attachement_path : implode("#<>#", $attachement_path); $mail->setAttachmentPaths($attachement_path); } $this->create($mail); if ($doNotSend !== true) { if ($doNotSend !== true) { try { $email = $this->transform($mail, $module); $adresses = $email->getTo(); $adresse = $email->getFrom(); $this->getMailer()->send($email); $mailSymfony = $this->transform($mail, $module); if ($redirect === true) { $mailSymfony = $this->prepareMessageForRedirection($mailSymfony, $module); } $this->getMailer()->send($mailSymfony, $module); } catch (TransportExceptionInterface $e) { throw new RuntimeException("Échec de l'envoi du message", 0, $e); } Loading @@ -267,10 +267,78 @@ class MailService { $mail->setStatusEnvoi(Mail::NOTSENT); } $this->update($mail); return $mail; } public function send(Email $mail, ?string $module = null): void { $doNotSend = $this->fetchValueFromConfig('do_not_send', $module); $redirect = $this->fetchValueFromConfig('redirect', $module); if ($doNotSend) { return; } if ($redirect) { $mail = $this->prepareMessageForRedirection($mail, $module); } try { $this->getMailer()->send($mail); } catch (TransportExceptionInterface $e) { throw new RuntimeException("Échec de l'envoi du message", 0, $e); } } protected function prepareMessageForRedirection(Email $mail, ?string $module = null): Email { // On crée un clone $redirMail = clone($mail); // Redirection effective $redirMail->getHeaders()->remove('To'); // Supprime tous les To $redirMail->getHeaders()->remove('Cc'); // Supprime tous les CC $redirMail->getHeaders()->remove('Bcc'); // Supprime tous les BCC $redirectTo = (array)$this->fetchValueFromConfig('redirect_to', $module); foreach ($redirectTo as $to) { $redirMail->addTo($to); } // Modification du sujet $redirMail->subject($mail->getSubject() . " {REDIR}"); // Modification du corps $to = []; $cc = []; $bcc = []; foreach ($mail->getTo() as $addr) { $to[] = $addr->toString(); } foreach ($mail->getCc() as $addr) { $cc[] = $addr->toString(); } foreach ($mail->getBcc() as $addr) { $bcc[] = $addr->toString(); } $to = implode(", ", $to); $cc = implode(", ", $cc); $bcc = implode(", ", $bcc); if ($textBody = $mail->getTextBody()) { $textBody .= sprintf(self::BODY_TEXT_TEMPLATE, $to, $cc, $bcc); $redirMail->text($textBody); } if ($htmlBody = $mail->getHtmlBody()) { $htmlBody .= sprintf(self::BODY_HTML_TEMPLATE, $to, $cc, $bcc); $redirMail->html($htmlBody); } return $redirMail; } /** TODO : Le reenvoi ne tient pas compte du module ... */ public function reenvoi(Mail $mail): Mail { Loading @@ -285,15 +353,16 @@ class MailService { } /** @return Mail[] */ public function getMailsWithFiltre(array $filtres): array { $qb = $this->createQueryBuilder(); if (isset($filtres['statut']) AND $filtres['statut'] !== '') { if (isset($filtres['statut']) and $filtres['statut'] !== '') { $qb = $qb->andWhere('mail.statusEnvoi = :statut')->setParameter('statut', $filtres['statut']); } if (isset($filtres['date']) AND $filtres['date'] !== '') { if (isset($filtres['date']) and $filtres['date'] !== '') { try { $date = (new DateTime())->sub(new DateInterval('P' . $filtres['date'])); } catch (Exception $e) { Loading Loading
src/UnicaenMail/Service/Mail/MailService.php +167 −98 Original line number Diff line number Diff line Loading @@ -8,28 +8,51 @@ use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\QueryBuilder; use DoctrineModule\Persistence\ProvidesObjectManager; use Exception; use RuntimeException; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Mime\Email; use UnicaenMail\Entity\Db\Mail; use Laminas\Mail\Message; use Laminas\Mime\Message as MimeMessage; use Laminas\Mime\Mime; use Laminas\Mime\Part; use Laminas\Mvc\Controller\AbstractActionController; use RuntimeException; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Mime\Email; use UnicaenMail\Entity\Db\Mail; use UnicaenMail\Exception\NotFoundConfigException; class MailService { class MailService { use ProvidesObjectManager; const BODY_TEXT_TEMPLATE = <<<EOS ----------------------------------------------------------------------- Ce mail a été redirigé. Destinataires originaux : To: %s Cc: %s Bcc: %s EOS; const BODY_HTML_TEMPLATE = <<<EOS <p>Ce mail a été redirigé.</p> <p> Destinataires originaux :<br /> To: %s<br /> Cc: %s<br /> Bcc: %s </p> EOS; private ?Mailer $mailer; public function getMailer(): ?Mailer { return $this->mailer; } public function setMailer(?Mailer $mailer): void { $this->mailer = $mailer; Loading @@ -39,6 +62,7 @@ class MailService { private ?string $entityClass = null; private array $config = []; /** * @param string $entityClass * @return MailService Loading @@ -49,17 +73,20 @@ class MailService { return $this; } public function setConfig(array $config): void { $this->config = $config; } public function createMailEntity() : Object public function createMailEntity(): object { $entity = new $this->entityClass(); return $entity; } /** GESTION DES ENTITES *******************************************************************************************/ public function create(Mail $mail): Mail Loading @@ -69,12 +96,14 @@ class MailService { return $mail; } public function update(Mail $mail): Mail { $this->objectManager->flush($mail); return $mail; } public function delete(Mail $mail): Mail { $this->objectManager->remove($mail); Loading @@ -82,6 +111,7 @@ class MailService { return $mail; } /** REQUETAGE *****************************************************************************************************/ public function createQueryBuilder(): QueryBuilder Loading @@ -90,6 +120,7 @@ class MailService { return $qb; } /** * @param string $champ * @param string $ordre Loading @@ -104,6 +135,7 @@ class MailService { return $result; } public function getMailsByMotClef(string $motClef, string $champ = 'dateEnvoi', string $ordre = 'DESC'): array { // todo ici un fix sal au probleme de MotClef1 === MotClef123 avec MotClef1 inclu dans MotClef123 Loading @@ -116,6 +148,7 @@ class MailService { return $result; } public function getMail(?int $id): ?Mail { $qb = $this->createQueryBuilder() Loading @@ -129,6 +162,7 @@ class MailService { return $result; } public function getRequestedMail(AbstractActionController $controller, string $param = 'mail'): ?Mail { $id = $controller->params()->fromRoute($param); Loading @@ -154,62 +188,31 @@ class MailService { return $value; } /** Transforme un mail Unicaen en Mail Symfony */ public function transform(Mail $mail, ?string $module = null): Email { try { $fromEmail = $this->fetchValueFromConfig('from_email', $module); $fromName = $this->fetchValueFromConfig('from_name', $module); $subjectPrefix = $this->fetchValueFromConfig('subject_prefix', $module); $redirect = $this->fetchValueFromConfig('redirect', $module); $redirectTo = $this->fetchValueFromConfig('redirect_to', $module); } catch (NotFoundConfigException $e) { throw new RuntimeException("Un problème est survenu lors de la récupération de valeurs de config", 0, $e); } $to = (is_string($mail->getDestinataires()))?explode(',',$mail->getDestinataires()):[]; $co = (is_string($mail->getCopies()))?explode(',',$mail->getCopies()):[]; $sujet = "[".$subjectPrefix. "] ".$mail->getSujet(); $corps = "<p><i>Ce courrier électronique vous a été adressé <strong>automatiquement</strong> par l'application ".$subjectPrefix.". </i></p>" . $mail->getCorps(); if ($redirect) { $to = $redirectTo; $sujet .= " {REDIR}"; $corps .= "<br/><br/><hr/><br/>"; $corps .= "Initialement envoyé à :"; $corps .= "<ul>"; foreach (explode(",",$mail->getDestinatairesInitials()) as $t) $corps .= "<li>" . $t . "</li>"; $corps .= "</ul>"; if ($mail->getCopies() !== null && !empty($co)) { $corps .= "Copie à :"; $corps .= "<ul>"; foreach ($co as $e) $corps .= "<li>".$e."</li>"; $corps .= "</ul>"; } } $message = (new Email()) ->from("'\"".$fromName."\" <".$fromEmail.">'") ->subject($sujet) ->text(strip_tags($corps)) ->html($corps); $message->to(...$to); $attachments = ($mail->getAttachmentPaths())?explode("#<>#",$mail->getAttachmentPaths()):[]; foreach ($attachments as $path) { $basename = basename($path); $extension = (explode('.', $basename)[1])??'bin'; $message->attachFromPath($path, $basename, 'application/' . $extension); } if (!$redirect) { if ($co !== null and !empty($co) and $co !== ['']) $message->cc(...$co); $mailSymfony = new Email(); $mailSymfony->from("'\"" . $fromName . "\" <" . $fromEmail . ">'"); $adresseToArray = $redirect ? explode(',', $mail->getDestinatairesInitials()) : (explode(',', $mail->getDestinataires())); $mailSymfony->to(...$adresseToArray); if ($mail->getCopies() !== null) { $adresseCcArray = explode(',', $mail->getCopies()); $mailSymfony->cc(...$adresseCcArray); } $mailSymfony->subject($mail->getSujet()); $mailSymfony->html($mail->getCorps()); $mailSymfony->text(strip_tags($mail->getCorps())); //if ($mail->getCopies()) $message = $message->bcc($mail->getCopies()); return $message; return $mailSymfony; } public function sendMail($to, $subject, $texte, ?string $module = null, $attachement_path = null, $copie = null): ?Mail Loading @@ -218,47 +221,44 @@ class MailService { $doNotSend = $this->fetchValueFromConfig('do_not_send', $module); $redirect = $this->fetchValueFromConfig('redirect', $module); $redirectTo = $this->fetchValueFromConfig('redirect_to', $module); $subjectPrefix = $this->fetchValueFromConfig('subject_prefix', $module); } catch (NotFoundConfigException $e) { throw new RuntimeException("Un problème est survenu lors de la récupération de valeurs de config", 0, $e); } if ($to=== null OR $to === "" OR $to === []) { if ($to === null or $to === "" or $to === []) { return null; } if (is_string($to)) $to=explode(',', $to); if (!is_array($to)) $to = [$to]; if (is_string($copie)) $copie=explode(',', $copie); if (!is_array($copie)) $copie = [$copie]; /** @var Mail $mail */ $mail = $this->createMailEntity(); $mail->setDateEnvoi(new DateTime()); $mail->setStatusEnvoi(Mail::PENDING); $mail->setDestinataires(is_array($to) ? implode(",", $to) : $to); if ($redirect) { $mail->setDestinatairesInitials(implode(",",$to)); $mail->setDestinataires(implode(",", $redirectTo)); $mail->setDestinatairesInitials($to); $mail->setDestinataires(implode(',',$redirectTo)); } else { $mail->setDestinataires(implode(",",$to)); $mail->setDestinataires($to); } if ($copie !== null and !empty($copie)) $mail->setCopies(implode(",", $copie)); $mail->setSujet($subject); $mail->setCorps($texte); if ($copie !== null and !empty($copie)) $mail->setCopies($copie); $sujet = "[" . $subjectPrefix . "] " . $subject; $mail->setSujet($sujet); $corps = "<p><i>Ce courrier électronique vous a été adressé <strong>automatiquement</strong> par l'application " . $subjectPrefix . ". </i></p>" . $texte; $mail->setCorps($corps); if ($attachement_path !== null) { $attachement_path = (is_string($attachement_path)) ? $attachement_path : implode("#<>#", $attachement_path); $mail->setAttachmentPaths($attachement_path); } $this->create($mail); if ($doNotSend !== true) { if ($doNotSend !== true) { try { $email = $this->transform($mail, $module); $adresses = $email->getTo(); $adresse = $email->getFrom(); $this->getMailer()->send($email); $mailSymfony = $this->transform($mail, $module); if ($redirect === true) { $mailSymfony = $this->prepareMessageForRedirection($mailSymfony, $module); } $this->getMailer()->send($mailSymfony, $module); } catch (TransportExceptionInterface $e) { throw new RuntimeException("Échec de l'envoi du message", 0, $e); } Loading @@ -267,10 +267,78 @@ class MailService { $mail->setStatusEnvoi(Mail::NOTSENT); } $this->update($mail); return $mail; } public function send(Email $mail, ?string $module = null): void { $doNotSend = $this->fetchValueFromConfig('do_not_send', $module); $redirect = $this->fetchValueFromConfig('redirect', $module); if ($doNotSend) { return; } if ($redirect) { $mail = $this->prepareMessageForRedirection($mail, $module); } try { $this->getMailer()->send($mail); } catch (TransportExceptionInterface $e) { throw new RuntimeException("Échec de l'envoi du message", 0, $e); } } protected function prepareMessageForRedirection(Email $mail, ?string $module = null): Email { // On crée un clone $redirMail = clone($mail); // Redirection effective $redirMail->getHeaders()->remove('To'); // Supprime tous les To $redirMail->getHeaders()->remove('Cc'); // Supprime tous les CC $redirMail->getHeaders()->remove('Bcc'); // Supprime tous les BCC $redirectTo = (array)$this->fetchValueFromConfig('redirect_to', $module); foreach ($redirectTo as $to) { $redirMail->addTo($to); } // Modification du sujet $redirMail->subject($mail->getSubject() . " {REDIR}"); // Modification du corps $to = []; $cc = []; $bcc = []; foreach ($mail->getTo() as $addr) { $to[] = $addr->toString(); } foreach ($mail->getCc() as $addr) { $cc[] = $addr->toString(); } foreach ($mail->getBcc() as $addr) { $bcc[] = $addr->toString(); } $to = implode(", ", $to); $cc = implode(", ", $cc); $bcc = implode(", ", $bcc); if ($textBody = $mail->getTextBody()) { $textBody .= sprintf(self::BODY_TEXT_TEMPLATE, $to, $cc, $bcc); $redirMail->text($textBody); } if ($htmlBody = $mail->getHtmlBody()) { $htmlBody .= sprintf(self::BODY_HTML_TEMPLATE, $to, $cc, $bcc); $redirMail->html($htmlBody); } return $redirMail; } /** TODO : Le reenvoi ne tient pas compte du module ... */ public function reenvoi(Mail $mail): Mail { Loading @@ -285,15 +353,16 @@ class MailService { } /** @return Mail[] */ public function getMailsWithFiltre(array $filtres): array { $qb = $this->createQueryBuilder(); if (isset($filtres['statut']) AND $filtres['statut'] !== '') { if (isset($filtres['statut']) and $filtres['statut'] !== '') { $qb = $qb->andWhere('mail.statusEnvoi = :statut')->setParameter('statut', $filtres['statut']); } if (isset($filtres['date']) AND $filtres['date'] !== '') { if (isset($filtres['date']) and $filtres['date'] !== '') { try { $date = (new DateTime())->sub(new DateInterval('P' . $filtres['date'])); } catch (Exception $e) { Loading