src/CmsBundle/Util/Mailer.php line 37

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.         $this->message->setReplyTo($email);
  165.         return $this;
  166.     }
  167.     /**
  168.      * Send Settings
  169.      *
  170.      * @param mixed $value Settings
  171.      */
  172.     public function setSettings($Settings){
  173.         $this->Settings $Settings;
  174.         return $this;
  175.     }
  176.     /**
  177.      * Send carbon copy to...
  178.      *
  179.      * @param mixed $value Emailaddress
  180.      */
  181.     public function setBcc($value){
  182.         if($this->Settings->getTest() && $this->ignoreTestmode == false){
  183.             $value explode(';'$this->Settings->getAdminEmail());
  184.         }
  185.         foreach($value as $k => $v){
  186.             $bcc = new Address($v);
  187.             $this->message->addBcc($bcc);
  188.         }
  189.         return $this;
  190.     }
  191.     /**
  192.      * Set sender...
  193.      *
  194.      * @param string $value Emailaddress
  195.      */
  196.     public function setSender($value){
  197.         $this->message->sender($value);
  198.         return $this;
  199.     }
  200.     /**
  201.      * Set return (bounce) path...
  202.      *
  203.      * @param string $value Emailaddress
  204.      */
  205.     public function returnPath($value){
  206.         $this->message->returnPath($value);
  207.         return $this;
  208.     }
  209.     /**
  210.      * Set the HTML body
  211.      *
  212.      * @param string $value HTML body
  213.      */
  214.     public function setHtmlBody($value$excludeMsg false){
  215.         if(!$excludeMsg && !empty($this->original_receivers) && $this->ignoreTestmode == false){
  216.             $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;
  217.         }
  218.         if (!empty($this->Settings->getColorSwap())) {
  219.             $value str_replace(array_keys($this->Settings->getColorSwap()), array_values($this->Settings->getColorSwap()), $value);
  220.         }
  221.         // Fixing special chars in Outlook/Live
  222.         $special_characters = [ 'À' => '&Agrave;''à' => '&agrave;''Á' => '&Aacute;''á' => '&aacute;''Â' => '&Acirc;''â' => '&acirc;''Ã' => '&Atilde;''ã' => '&atilde;''Ä' => '&Auml;''ä' => '&auml;''Å' => '&Aring;''å' => '&aring;''Æ' => '&AElig;''æ' => '&aelig;''Ç' => '&Ccedil;''ç' => '&ccedil;''È' => '&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;''Ù' => '&Ugrave;''ù' => '&ugrave;''Ú' => '&Uacute;''ú' => '&uacute;''Û' => '&Ucirc;''û' => '&ucirc;''Ü' => '&Uuml;''ü' => '&uuml;''Ÿ' => '&Yuml;''ÿ' => '&yuml;'];
  223.         $value str_replace(array_keys($special_characters), array_values($special_characters), $value);
  224.         $this->message->html($value'text/html');
  225.         return $this;
  226.     }
  227.     /**
  228.      * Set the plain body
  229.      *
  230.      * @param string $value plain body
  231.      */
  232.     public function setPlainBody($value){
  233.         if(!empty($this->original_receivers) && $this->ignoreTestmode == false){
  234.             $value 'Deze e-mail wordt origineel verstuurd naar:' "\n\n" implode(', '$this->original_receivers) . "\n\n" $value;
  235.         }
  236.         $this->message->text($value'text/plain');
  237.         return $this;
  238.     }
  239.     /**
  240.      * Set the HTML body from twig
  241.      *
  242.      * @param string $twigFile file to load
  243.      * @param string $params array of parameters to return to twig file
  244.      */
  245.     public function setTwigBody($twigFile$params = []){
  246.         if(!empty($this->original_receivers) && isset($params['message']) && $this->ignoreTestmode == false){
  247.             $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'];
  248.         }
  249.         $params['settings'] = $this->Settings;
  250.         $this->html $this->twig->render(
  251.             $twigFile,
  252.             $params
  253.         );
  254.         $this->html str_replace(array_keys($this->Settings->getColorSwap()), array_values($this->Settings->getColorSwap()), $this->html);
  255.         $this->setHtmlBody($this->htmltrue);
  256.         return $this;
  257.     }
  258.     /**
  259.      * Send email
  260.      *
  261.      * @return boolean response status
  262.      */
  263.     public function execute(){
  264.         $this->ignoreTestmode false;
  265.         $status false;
  266.         try {
  267.             $this->mailer->send($this->message);
  268.             $status true;
  269.         } catch (TransportException $e) {
  270.             // some error prevented the email sending; display an
  271.             // error message or try to resend the message
  272.         } catch (\Exception $e) {
  273.             // some error prevented the email sending; display an
  274.             // error message or try to resend the message
  275.         }
  276.         return $status;
  277.     }
  278.     /**
  279.      * Send email (forced, dont wait for nice response)
  280.      *
  281.      * @deprecated since 4.0 use execute() instead
  282.      *
  283.      * @return boolean response status
  284.      */
  285.     public function execute_forced(){
  286.         $status $this->execute();
  287.         /*if($status){
  288.             $spool = $this->mailer->getTransport()->getSpool();
  289.             $transport = $this->container->get('swiftmailer.transport.real');
  290.             if ($spool and $transport){
  291.                 $spool->flushQueue($transport);
  292.             }
  293.         }*/
  294.         $this->ignoreTestmode false;
  295.         return $status;
  296.     }
  297.     /**
  298.      * Get mailer transport
  299.      *
  300.      * @return Mailer
  301.      */
  302.     public function getTransport(){
  303.         return $this->mailer->getTransport();
  304.     }
  305.     /**
  306.      * Attach calandar event string
  307.      *
  308.      * @param array $attendees List of attendees in format ['random@email.nl' => 'Firstname Lastname']
  309.      * @param string $title Short event title (required)
  310.      * @param string $location The event location
  311.      * @param string $description The long description in the event detail
  312.      * @param DateTime $start The start date and time
  313.      * @param DateTime $start The end date and time
  314.      * @param string $email The e-mailadres used as organiser (empty = system defaults from Settings)
  315.      * @param string $name The (full-)name used as organiser (empty = system defaults from Settings)
  316.      *
  317.      * @return Mailer
  318.      */
  319.     public function addCalendarEvent(array $attendees = [], string $title ''string $location ''string $description ''\DateTime $start null\DateTime $end null$email null$name null){
  320.         $endStr "";
  321.         if($end instanceof \DateTime){
  322.             $endStr "\nDTEND:".$end->format('Ymd\THis');
  323.         }
  324.         $now = new \DateTime();
  325.         if($email == null){ $email $this->Settings->getSystemEmail(); }
  326.         if($name == null){ $name $this->Settings->getSystemEmailFrom(); }
  327.         $attendeesStr '';
  328.         $attendeesList '\n\nDeelnemers:\n';
  329.         foreach($attendees as $att_email => $att_name){
  330.             $attendeesStr .= "\n" 'ATTENDEE;CN="' $att_name '";CUTYPE=INDIVIDUAL;PARTSTAT' "\n " '=ACCEPTED:mailto:' $att_email;
  331.             $attendeesList .= '\n' $att_name;
  332.         }
  333.         $icsContent 'BEGIN:VCALENDAR
  334.             VERSION:2.0
  335.             PRODID:-//Easify CMS//Ical event//NL
  336.             CALSCALE:GREGORIAN
  337.             METHOD:PUBLISH
  338.             BEGIN:VEVENT
  339.             DTSTART:' $start->format('Ymd\THis') . $endStr '
  340.             DTSTAMP:' $now->format('Ymd\THis') . '
  341.             ORGANIZER;CN=' $name ':mailto:' $email '
  342.             UID:' rand(51500) . $attendeesStr '
  343.             DESCRIPTION:' $description . (!empty($attendees) ? $attendeesList '') . '
  344.             LOCATION:' $location '
  345.             SEQUENCE:0
  346.             STATUS:CONFIRMED
  347.             SUMMARY:' $title '
  348.             TRANSP:OPAQUE
  349.             END:VEVENT
  350.             END:VCALENDAR'
  351.         ;
  352.         $icsContent str_replace("\t"""$icsContent);
  353.         $icsContent preg_replace("/\n\s{2,}/""\n"$icsContent);
  354.         $fs        = new Filesystem();
  355.         $tmpFolder str_replace('src/CmsBundle/Util''public/uploads/'__DIR__);
  356.         $fileName  'meeting.ics';
  357.         $icfFile $fs->dumpFile($tmpFolder.$fileName$icsContent);
  358.         $this->addFile($tmpFolder.$fileName);
  359.         return $this;
  360.     }
  361.     /**
  362.      * Attach file
  363.      *
  364.      * @return Mailer
  365.      */
  366.     public function addFile($file$filename null){
  367.         $this->message->attachFromPath($file$filename);
  368.         return $this;
  369.     }
  370.     /**
  371.      * Attach embedded file
  372.      *
  373.      * @return $cid
  374.      */
  375.     public function embeddedFile($file){
  376.         $cid $this->message->embed(\Swift_Image::fromPath($file));
  377.         return $cid;
  378.     }
  379.     /**
  380.      * Attach file
  381.      *
  382.      * @return Mailer
  383.      */
  384.     public function addMedia(\App\CmsBundle\Entity\Media $file){
  385.         $this->message->attachFromPath($file->getAbsolutePath(), $file->getLabel());
  386.         return $this;
  387.     }
  388.     public function __toString(){
  389.         return $this->message->getBody();
  390.     }
  391. }