src/CmsBundle/Util/Mailer.php line 70

Open in your IDE?
  1. <?php
  2. namespace App\CmsBundle\Util;
  3. use Symfony\Component\Filesystem\Filesystem;
  4. use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. use Symfony\Component\Mailer\Exception\TransportException;
  9. use Symfony\Component\Mailer\MailerInterface;
  10. use Symfony\Component\Mime\Email;
  11. use Symfony\Component\Mime\Address;
  12. use Twig\Environment;
  13. /**
  14.  * Trinity mailer wrapper
  15.  */
  16. class Mailer{
  17.     protected $em;
  18.     protected $container;
  19.     protected $mailer;
  20.     protected $twig;
  21.     protected $message;
  22.     protected $Settings;
  23.     protected $language;
  24.     protected $languages;
  25.     protected $request;
  26.     protected $locale;
  27.     protected $ignoreTestmode false;
  28.     protected $original_receivers = [];
  29.     public $html '';
  30.     /**
  31.      * Construct the Trinity mailer
  32.      */
  33.     public function __construct(EntityManagerInterface $entityManagerContainerInterface $containerRequestStack $requestStackMailerInterface $mailerEnvironment $twig) {
  34.         $this->em        $entityManager;
  35.         $this->container $container;
  36.         $this->mailer    $mailer;
  37.         $this->twig      $twig;
  38.         $this->locale    $this->container->get('session')->get('_locale');
  39.         if($this->locale){
  40.             $this->language $this->em->getRepository('CmsBundle:Language')->findOneByLocale($this->locale);
  41.         }else{
  42.             $this->languages $this->em->getRepository('CmsBundle:Language')->findAll();
  43.             if(!empty($this->languages)){
  44.                 $this->language $this->languages[0];
  45.             }
  46.         }
  47.         $this->request $requestStack->getCurrentRequest();
  48.         if (!empty($this->request)) {
  49.             $this->Settings $this->em->getRepository('CmsBundle:Settings')->findByLanguage($this->languagestr_replace('www.'''$this->request->getHttpHost()));
  50.         }
  51.         if(is_null($this->Settings) || is_null($this->Settings->getId())){
  52.             $this->Settings $this->em->getRepository('CmsBundle:Settings')->findByLanguage($this->language);
  53.         }
  54.         $this->message = (new Email());
  55.         if($this->Settings){
  56.             if($this->Settings->getTest()){
  57.                 $this->message->from(new Address(explode(';'$this->Settings->getAdminEmail())[0], $this->Settings->getAdminEmailFrom()));
  58.                 $this->message->sender(new Address(explode(';'$this->Settings->getAdminEmail())[0]));
  59.                 $this->message->returnPath(new Address(explode(';'$this->Settings->getAdminEmail())[0]));
  60.             }else{
  61.                 $this->message->from(new Address($this->Settings->getSystemEmail(), $this->Settings->getSystemEmailFrom()));
  62.                 $this->message->sender($this->Settings->getSystemEmail());
  63.                 $this->message->returnPath($this->Settings->getSystemEmail());
  64.             }
  65.         }
  66.         $this->ignoreTestmode false;
  67.     }
  68.     public function init($reset true){
  69.         if ($reset) {
  70.             $this->locale    $this->container->get('session')->get('_locale');
  71.             if($this->locale){
  72.                 $this->language $this->em->getRepository('CmsBundle:Language')->findOneByLocale($this->locale);
  73.             }else{
  74.                 $this->languages $this->em->getRepository('CmsBundle:Language')->findAll();
  75.                 $this->language $this->languages[0];
  76.             }
  77.             if (!empty($this->request)) {
  78.                 $this->Settings $this->em->getRepository('CmsBundle:Settings')->findByLanguage($this->languagestr_replace('www.'''$this->request->getHttpHost()));
  79.             }
  80.             if(is_null($this->Settings) || is_null($this->Settings->getId())){
  81.                 $this->Settings $this->em->getRepository('CmsBundle:Settings')->findByLanguage($this->language);
  82.             }
  83.         }
  84.         $this->message = (new Email());
  85.         if($this->Settings->getTest() && $this->ignoreTestmode == false){
  86.             $this->message->from(new Address(explode(';'$this->Settings->getAdminEmail())[0], $this->Settings->getAdminEmailFrom()));
  87.             $this->message->sender(new Address(explode(';'$this->Settings->getAdminEmail())[0]));
  88.             $this->message->returnPath(new Address(explode(';'$this->Settings->getAdminEmail())[0]));
  89.         }else{
  90.             $this->message->from(new Address($this->Settings->getSystemEmail(), $this->Settings->getSystemEmailFrom()));
  91.             $this->message->sender($this->Settings->getSystemEmail());
  92.             $this->message->returnPath($this->Settings->getSystemEmail());
  93.         }
  94.     }
  95.     /**
  96.      * Ignore test mode
  97.      */
  98.     public function setIgnoreTestmode(){
  99.         $this->ignoreTestmode true;
  100.         return $this;
  101.     }
  102.     /**
  103.      * E-mail subject
  104.      *
  105.      * @param string $value Email subject
  106.      */
  107.     public function setSubject($value){
  108.         if($this->Settings->getTest() && $this->ignoreTestmode == false){
  109.             $value 'TEST: ' $value;
  110.         }
  111.         $this->message->subject($value);
  112.         return $this;
  113.     }
  114.     /**
  115.      * Send email to
  116.      *
  117.      * @param mixed $value Emailaddress
  118.      */
  119.     public function setTo($value){
  120.         if($this->Settings->getTest() && $this->ignoreTestmode == false){
  121.             $this->original_receivers = (!is_array($value) ? [$value] : $value);
  122.             $value explode(';'$this->Settings->getAdminEmail());
  123.         }else{
  124.             $this->original_receivers = [];
  125.         }
  126.         if(is_array($value)){
  127.             $newValue = [];
  128.             foreach($value as $emailOrIndex => $nameOrEmail){
  129.                 if(is_string($emailOrIndex)){
  130.                     $newValue[] = new Address($emailOrIndex$nameOrEmail);
  131.                 }else{
  132.                     $newValue[] = new Address($nameOrEmail);
  133.                 }
  134.             }
  135.             $value $newValue;
  136.         }
  137.         if(is_array($value)){
  138.             foreach($value as $Address){
  139.                 $this->message->addTo($Address);
  140.             }
  141.         }else{
  142.             $this->message->to($value);
  143.         }
  144.         return $this;
  145.     }
  146.     /**
  147.      * Send email to
  148.      *
  149.      * @param mixed $value Emailaddress
  150.      */
  151.     public function setFrom($email$name){
  152.         if($this->Settings->getTest() && $this->ignoreTestmode == false){
  153.             $value explode(';'$this->Settings->getAdminEmail())[0];
  154.         }
  155.         $this->message->from(new Address($email$name));
  156.         return $this;
  157.     }
  158.     /**
  159.      * Send reply to
  160.      *
  161.      * @param mixed $value Emailaddress
  162.      */
  163.     public function setReplyTo($email){
  164.         if(is_array($email)){
  165.             foreach($email as $email => $name){
  166.                 $email = new Address($email$name);
  167.             }
  168.         }
  169.         $this->message->replyTo($email);
  170.         return $this;
  171.     }
  172.     /**
  173.      * Send Settings
  174.      *
  175.      * @param mixed $value Settings
  176.      */
  177.     public function setSettings($Settings){
  178.         $this->Settings $Settings;
  179.         return $this;
  180.     }
  181.     /**
  182.      * Send carbon copy to...
  183.      *
  184.      * @param mixed $value Emailaddress
  185.      */
  186.     public function setBcc($value){
  187.         if($this->Settings->getTest() && $this->ignoreTestmode == false){
  188.             $value explode(';'$this->Settings->getAdminEmail());
  189.         }
  190.         foreach($value as $k => $v){
  191.             $bcc = new Address($v);
  192.             $this->message->addBcc($bcc);
  193.         }
  194.         return $this;
  195.     }
  196.     /**
  197.      * Set sender...
  198.      *
  199.      * @param string $value Emailaddress
  200.      */
  201.     public function setSender($value){
  202.         $this->message->sender($value);
  203.         return $this;
  204.     }
  205.     /**
  206.      * Set return (bounce) path...
  207.      *
  208.      * @param string $value Emailaddress
  209.      */
  210.     public function returnPath($value){
  211.         $this->message->returnPath($value);
  212.         return $this;
  213.     }
  214.     /**
  215.      * Set the HTML body
  216.      *
  217.      * @param string $value HTML body
  218.      */
  219.     public function setHtmlBody($value$excludeMsg false){
  220.         if(!$excludeMsg && !empty($this->original_receivers) && $this->ignoreTestmode == false){
  221.             $value '<div style="background:#eee;padding:10px;font-size:11px;margin-bottom:15px;"><p>Deze e-mail wordt origineel verstuurd naar:</p><p>' implode(', '$this->original_receivers) . '</p></div>' $value;
  222.         }
  223.         if (!empty($this->Settings->getColorSwap())) {
  224.             $value str_replace(array_keys($this->Settings->getColorSwap()), array_values($this->Settings->getColorSwap()), $value);
  225.         }
  226.         // Fixing special chars in Outlook/Live
  227.         $special_characters = [ 'À' => '&Agrave;''à' => '&agrave;''Á' => '&Aacute;''á' => '&aacute;''Â' => '&Acirc;''â' => '&acirc;''Ã' => '&Atilde;''ã' => '&atilde;''Ä' => '&Auml;''ä' => '&auml;''Å' => '&Aring;''å' => '&aring;''Æ' => '&AElig;''æ' => '&aelig;''Ç' => '&Ccedil;''ç' => '&ccedil;''?' => '&ETH;''?' => '&eth;''È' => '&Egrave;''è' => '&egrave;''É' => '&Eacute;''é' => '&eacute;''Ê' => '&Ecirc;''ê' => '&ecirc;''Ë' => '&Euml;''ë' => '&euml;''Ì' => '&Igrave;''ì' => '&igrave;''Í' => '&Iacute;''í' => '&iacute;''Î' => '&Icirc;''î' => '&icirc;''Ï' => '&Iuml;''ï' => '&iuml;''Ñ' => '&Ntilde;''ñ' => '&ntilde;''Ò' => '&Ograve;''ò' => '&ograve;''Ó' => '&Oacute;''ó' => '&oacute;''Ô' => '&Ocirc;''ô' => '&ocirc;''Õ' => '&Otilde;''õ' => '&otilde;''Ö' => '&Ouml;''ö' => '&ouml;''Ø' => '&Oslash;''ø' => '&oslash;''Œ' => '&OElig;''œ' => '&oelig;''ß' => '&szlig;''?' => '&THORN;''?' => '&thorn;''Ù' => '&Ugrave;''ù' => '&ugrave;''Ú' => '&Uacute;''ú' => '&uacute;''Û' => '&Ucirc;''û' => '&ucirc;''Ü' => '&Uuml;''ü' => '&uuml;''?' => '&Yacute;''?' => '&yacute;''Ÿ' => '&Yuml;''ÿ' => '&yuml;'];
  228.         $value str_replace(array_keys($special_characters), array_values($special_characters), $value);
  229.         $this->message->html($value'text/html');
  230.         return $this;
  231.     }
  232.     /**
  233.      * Set the plain body
  234.      *
  235.      * @param string $value plain body
  236.      */
  237.     public function setPlainBody($value){
  238.         if(!empty($this->original_receivers) && $this->ignoreTestmode == false){
  239.             $value 'Deze e-mail wordt origineel verstuurd naar:' "\n\n" implode(', '$this->original_receivers) . "\n\n" $value;
  240.         }
  241.         $this->message->text($value'text/plain');
  242.         return $this;
  243.     }
  244.     /**
  245.      * Set the HTML body from twig
  246.      *
  247.      * @param string $twigFile file to load
  248.      * @param string $params array of parameters to return to twig file
  249.      */
  250.     public function setTwigBody($twigFile$params = []){
  251.         if(!empty($this->original_receivers) && isset($params['message']) && $this->ignoreTestmode == false){
  252.             $params['message'] = '<div style="background:#eee;padding:10px;font-size:11px;margin-bottom:15px;"><p>Deze e-mail wordt origineel verstuurd naar:</p><p>' implode(', '$this->original_receivers) . '</p></div>' $params['message'];
  253.         }
  254.         $params['settings'] = $this->Settings;
  255.         $this->html $this->twig->render(
  256.             $twigFile,
  257.             $params
  258.         );
  259.         $this->html str_replace(array_keys($this->Settings->getColorSwap()), array_values($this->Settings->getColorSwap()), $this->html);
  260.         $this->setHtmlBody($this->htmltrue);
  261.         return $this;
  262.     }
  263.     /**
  264.      * Send email
  265.      *
  266.      * @return boolean response status
  267.      */
  268.     public function execute(){
  269.         $this->ignoreTestmode false;
  270.         $status false;
  271.         try {
  272.             $this->mailer->send($this->message);
  273.             $status true;
  274.         } catch (TransportException $e) {
  275.             // some error prevented the email sending; display an
  276.             // error message or try to resend the message
  277.         } catch (\Exception $e) {
  278.             // some error prevented the email sending; display an
  279.             // error message or try to resend the message
  280.         }
  281.         return $status;
  282.     }
  283.     /**
  284.      * Send email (forced, dont wait for nice response)
  285.      *
  286.      * @deprecated since 4.0 use execute() instead
  287.      *
  288.      * @return boolean response status
  289.      */
  290.     public function execute_forced(){
  291.         $status $this->execute();
  292.         /*if($status){
  293.             $spool = $this->mailer->getTransport()->getSpool();
  294.             $transport = $this->container->get('swiftmailer.transport.real');
  295.             if ($spool and $transport){
  296.                 $spool->flushQueue($transport);
  297.             }
  298.         }*/
  299.         $this->ignoreTestmode false;
  300.         return $status;
  301.     }
  302.     /**
  303.      * Get mailer transport
  304.      *
  305.      * @return Mailer
  306.      */
  307.     public function getTransport(){
  308.         return $this->mailer->getTransport();
  309.     }
  310.     /**
  311.      * Attach calandar event string
  312.      *
  313.      * @param array $attendees List of attendees in format ['random@email.nl' => 'Firstname Lastname']
  314.      * @param string $title Short event title (required)
  315.      * @param string $location The event location
  316.      * @param string $description The long description in the event detail
  317.      * @param DateTime $start The start date and time
  318.      * @param DateTime $start The end date and time
  319.      * @param string $email The e-mailadres used as organiser (empty = system defaults from Settings)
  320.      * @param string $name The (full-)name used as organiser (empty = system defaults from Settings)
  321.      *
  322.      * @return Mailer
  323.      */
  324.     public function addCalendarEvent(array $attendees = [], string $title ''string $location ''string $description ''\DateTime $start null\DateTime $end null$email null$name null){
  325.         $endStr "";
  326.         if($end instanceof \DateTime){
  327.             $endStr "\nDTEND:".$end->format('Ymd\THis');
  328.         }
  329.         $now = new \DateTime();
  330.         if($email == null){ $email $this->Settings->getSystemEmail(); }
  331.         if($name == null){ $name $this->Settings->getSystemEmailFrom(); }
  332.         $attendeesStr '';
  333.         $attendeesList '\n\nDeelnemers:\n';
  334.         foreach($attendees as $att_email => $att_name){
  335.             $attendeesStr .= "\n" 'ATTENDEE;CN="' $att_name '";CUTYPE=INDIVIDUAL;PARTSTAT' "\n " '=ACCEPTED:mailto:' $att_email;
  336.             $attendeesList .= '\n' $att_name;
  337.         }
  338.         $icsContent 'BEGIN:VCALENDAR
  339.             VERSION:2.0
  340.             PRODID:-//Easify CMS//Ical event//NL
  341.             CALSCALE:GREGORIAN
  342.             METHOD:PUBLISH
  343.             BEGIN:VEVENT
  344.             DTSTART:' $start->format('Ymd\THis') . $endStr '
  345.             DTSTAMP:' $now->format('Ymd\THis') . '
  346.             ORGANIZER;CN=' $name ':mailto:' $email '
  347.             UID:' rand(51500) . $attendeesStr '
  348.             DESCRIPTION:' $description . (!empty($attendees) ? $attendeesList '') . '
  349.             LOCATION:' $location '
  350.             SEQUENCE:0
  351.             STATUS:CONFIRMED
  352.             SUMMARY:' $title '
  353.             TRANSP:OPAQUE
  354.             END:VEVENT
  355.             END:VCALENDAR'
  356.         ;
  357.         $icsContent str_replace("\t"""$icsContent);
  358.         $icsContent preg_replace("/\n\s{2,}/""\n"$icsContent);
  359.         $fs        = new Filesystem();
  360.         $tmpFolder str_replace('src/CmsBundle/Util''public/uploads/'__DIR__);
  361.         $fileName  'meeting.ics';
  362.         $icfFile $fs->dumpFile($tmpFolder.$fileName$icsContent);
  363.         $this->addFile($tmpFolder.$fileName);
  364.         return $this;
  365.     }
  366.     /**
  367.      * Attach file
  368.      *
  369.      * @return Mailer
  370.      */
  371.     public function addFile($file$filename null){
  372.         $this->message->attachFromPath($file$filename);
  373.         return $this;
  374.     }
  375.     /**
  376.      * Attach embedded file
  377.      *
  378.      * @return $cid
  379.      */
  380.     public function embeddedFile($file){
  381.         $cid $this->message->embed(\Swift_Image::fromPath($file));
  382.         return $cid;
  383.     }
  384.     /**
  385.      * Attach file
  386.      *
  387.      * @return Mailer
  388.      */
  389.     public function addMedia(\App\CmsBundle\Entity\Media $file){
  390.         $this->message->attachFromPath($file->getAbsolutePath(), $file->getLabel());
  391.         return $this;
  392.     }
  393.     public function __toString(){
  394.         return $this->message->getBody();
  395.     }
  396. }