Advertisement
Guest User

Untitled

a guest
May 27th, 2019
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.54 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Modules\Email\Services;
  4.  
  5. use App\Modules\Email\Exceptions\InvalidRecipientTypeException;
  6. use Illuminate\Contracts\Config\Repository as Config;
  7. use Illuminate\Mail\Message;
  8. use Mail;
  9. use Swift_Mailer;
  10. use Swift_Transport_Esmtp_AuthHandler;
  11. use App;
  12. use Config as AppConfig;
  13.  
  14. class EmailSenderService
  15. {
  16.     /**
  17.      * Config
  18.      *
  19.      * @var Config
  20.      */
  21.     protected $config;
  22.  
  23.     /**
  24.      * Custom e-mail send configuration
  25.      *
  26.      * @var array|null
  27.      */
  28.     protected $sendConfig;
  29.  
  30.     public function __construct(Config $config)
  31.     {
  32.         $this->config = $config;
  33.         $this->clearOneTimeSendConfig();
  34.     }
  35.  
  36.     /**
  37.      * Set one time send configuration
  38.      *
  39.      * @param $sendConfig
  40.      */
  41.     public function setOneTimeSendConfig($sendConfig)
  42.     {
  43.         $this->sendConfig = $sendConfig;
  44.     }
  45.  
  46.     /**
  47.      * Clear one time send configuration
  48.      */
  49.     protected function clearOneTimeSendConfig()
  50.     {
  51.         $this->sendConfig = null;
  52.     }
  53.  
  54.     /**
  55.      * Send e-mail of type $type (depending on configuration)
  56.      *
  57.      * @param string $type
  58.      * @param string $subject
  59.      * @param string $body
  60.      */
  61.     public function sendType($type, $subject, $body)
  62.     {
  63.         if ($this->config->get("email.actions.{$type}.enabled") === true) {
  64.             $from = $this->config->get("email.actions.{$type}.from");
  65.             $to = $this->config->get("email.actions.{$type}.to");
  66.  
  67.             $this->sendPlain($to, $from, $subject, $body);
  68.         }
  69.     }
  70.  
  71.     /**
  72.      * Send html e-mail (with optional attachments)
  73.      *
  74.      * @param string $to
  75.      * @param string $from
  76.      * @param string $subject
  77.      * @param string $view
  78.      * @param array $data
  79.      * @param array $attachments Array of attachment. It can contains location
  80.      * of attachments or array of objects (containing properties location and
  81.      * optionally mime and filename to use different filename than saved in
  82.      * storage)
  83.      */
  84.     public function sendHtml(
  85.         $to,
  86.         $from,
  87.         $subject,
  88.         $view,
  89.         array $data = [],
  90.         array $attachments = []
  91.     )
  92.     {
  93.         Mail::send($view, $data,
  94.             function ($message) use ($to, $from, $subject, $attachments) {
  95.                 /** @var Message $message */
  96.                 $message->from($from);
  97.                 //if to is array then loop and add all emails as recipients
  98.                 if (is_array($to)) {
  99.                     foreach ($to as $sendToEmail) {
  100.                         $message->to($sendToEmail);
  101.                     }
  102.                 } else {
  103.                     $message->to($to);
  104.                 }
  105.                 $message->subject($subject);
  106.  
  107.                 // @todo use below addAttachments method instead of below code
  108.                 foreach ($attachments as $attachment) {
  109.                     $options = [];
  110.  
  111.                     if (is_object($attachment) || is_array($attachment)) {
  112.                         $attachment = (object)$attachment;
  113.                         $location = $attachment->location;
  114.                         if (isset($attachment->mime)) {
  115.                             $options['mime'] = $attachment->mime;
  116.                         }
  117.                         if (isset($attachment->filename)) {
  118.                             $options['as'] = $attachment->filename;
  119.                         }
  120.                     } else {
  121.                         $location = $attachment;
  122.                     }
  123.  
  124.                     $message->attach($location, $options);
  125.                 }
  126.             });
  127.     }
  128.  
  129.     /**
  130.      * Add attachments to given message
  131.      *
  132.      * @param Message $message
  133.      * @param array $attachments
  134.      */
  135.     protected function addAttachments(Message $message, array $attachments)
  136.     {
  137.         foreach ($attachments as $attachment) {
  138.             $options = [];
  139.  
  140.             if (is_object($attachment) || is_array($attachment)) {
  141.                 $attachment = (object)$attachment;
  142.                 $location = $attachment->location;
  143.                 if (isset($attachment->mime)) {
  144.                     $options['mime'] = $attachment->mime;
  145.                 }
  146.                 if (isset($attachment->filename)) {
  147.                     $options['as'] = $attachment->filename;
  148.                 }
  149.             } else {
  150.                 $location = $attachment;
  151.             }
  152.  
  153.             $message->attach($location, $options);
  154.         }
  155.     }
  156.  
  157.     /**
  158.      * Send e-mail in plain text
  159.      *
  160.      * @param string $to
  161.      * @param string $from
  162.      * @param string $subject
  163.      * @param string $body
  164.      * @param string|null $fromName
  165.      * @param array $attachments Array of attachment. It can contains location
  166.      * of attachments or array of objects (containing properties location and
  167.      * optionally mime and filename to use different filename than saved in
  168.      * storage)
  169.      */
  170.     public function sendPlain(
  171.         $to,
  172.         $from,
  173.         $subject,
  174.         $body,
  175.         $fromName = null,
  176.         array $attachments = []
  177.     )
  178.     {
  179.         Mail::raw($body,
  180.             function ($message) use ($to, $from, $fromName, $subject, $attachments) {
  181.                 /** @var Message $message */
  182.                 $message->from($from, $fromName);
  183.                 $message->to($to);
  184.                 $message->subject($subject);
  185.                 $this->addAttachments($message, $attachments);
  186.             });
  187.     }
  188.  
  189.     /**
  190.      * Send e-mail together with cc, bcc and optional attachments
  191.      *
  192.      * @param string $to
  193.      * @param string $from
  194.      * @param string $cc
  195.      * @param string $bcc
  196.      * @param string $subject
  197.      * @param string $body
  198.      * @param array $attachments
  199.      * @return boolean
  200.      */
  201.     public function sendAdvancedEmail(
  202.         $to,
  203.         $from,
  204.         $cc,
  205.         $bcc,
  206.         $subject,
  207.         $body,
  208.         array $attachments = []
  209.     )
  210.     {
  211.         $mailer = null;
  212.  
  213.         if ($this->sendConfig !== null) {
  214.             /** @var Swift_Mailer $mailer */
  215.             $mailer = Mail::getSwiftMailer();
  216.  
  217.             /** @var Swift_Transport_Esmtp_AuthHandler $auth */
  218.             $transport = $mailer->getTransport();
  219.             $transport = $transport::newInstance($this->sendConfig['host'],
  220.                 $this->sendConfig['port'])
  221.                 ->setUserName($this->sendConfig['username'])
  222.                 ->setPassword($this->sendConfig['password']);
  223.  
  224.             $newMailer = $mailer::newInstance($transport);
  225.  
  226.             Mail::setSwiftMailer($newMailer);
  227.         }
  228.  
  229.         Mail::raw($body, function ($message) use (
  230.             $to,
  231.             $from,
  232.             $cc,
  233.             $bcc,
  234.             $subject,
  235.             $attachments
  236.         ) {
  237.             /** @var Message $message */
  238.             if ($from) {
  239.                 list($from, $name) = $this->getValidRecipient($from);
  240.             } else {
  241.                 $from = $this->config->get('mail.from.address');
  242.                 $name = $this->config->get('mail.from.name');
  243.             }
  244.             $message->from($from, $name);
  245.             $this->addRecipients($message, $to, 'to');
  246.             $this->addRecipients($message, $cc, 'cc');
  247.             $this->addRecipients($message, $bcc, 'bcc');
  248.  
  249.             $message->subject($subject);
  250.             foreach ($attachments as $name => $content) {
  251.                 $message->attachData($content, $name);
  252.             }
  253.         });
  254.  
  255.         // restoring previous mailer
  256.         if ($this->sendConfig !== null) {
  257.             Mail::setSwiftMailer($mailer);
  258.         }
  259.  
  260.         return !Mail::failures();
  261.     }
  262.  
  263.     /**
  264.      * Add recipients of given type for email
  265.      *
  266.      * @param Message $message
  267.      * @param array|string $emails
  268.      * @param string $type
  269.      *
  270.      * @throws \Exception
  271.      */
  272.     protected function addRecipients($message, $emails, $type = 'to')
  273.     {
  274.         $allowedTypes = ['to', 'cc', 'bcc'];
  275.         if (!in_array($type, $allowedTypes)) {
  276.             $exp = App::make(InvalidRecipientTypeException::class);
  277.             $exp->setData(['type' => $type, 'allowed_types' => $allowedTypes]);
  278.             throw $exp;
  279.         }
  280.  
  281.         if ($emails) {
  282.             if (!is_array($emails)) {
  283.                 $emails = [$emails];
  284.             }
  285.             foreach ($emails as $item) {
  286.                 list($email, $name) = $this->getValidRecipient($item);
  287.                 if (trim($email)) {
  288.                     $message->{$type}($email, $name);
  289.                 }
  290.             }
  291.         }
  292.     }
  293.  
  294.     /**
  295.      * Explodes recipient to mail address and name
  296.      *
  297.      * @param string $address
  298.      *
  299.      * @return array
  300.      */
  301.     public function getValidRecipient($address)
  302.     {
  303.         preg_match('/(.*)<(.*)>/', $address, $matches);
  304.  
  305.         if (count($matches) == 3) {
  306.             $mail = trim($matches[2]);
  307.             $to = trim($matches[1]);
  308.         } else {
  309.             $mail = trim(trim(trim($address), '<>'));
  310.             $to = $mail;
  311.         }
  312.  
  313.         return [$mail, $to];
  314.     }
  315.  
  316.     /**
  317.      * Send html e-mail with custom transport config
  318.      *
  319.      * @param string $to
  320.      * @param array $from
  321.      * @param array $config
  322.      * @param string $subject
  323.      * @param string $view
  324.      * @param array $data
  325.      */
  326.     public function sendHtmlCustomConfig(
  327.         $to,
  328.         $from,
  329.         $config,
  330.         $subject,
  331.         $view,
  332.         array $data = []
  333.     )
  334.     {
  335.         //Change mail settings on the fly
  336.         AppConfig::set('mail.encryption', $config['encryption']);
  337.         AppConfig::set('mail.host', $config['host']);
  338.         AppConfig::set('mail.port', $config['port']);
  339.         AppConfig::set('mail.username', $config['username']);
  340.         AppConfig::set('mail.password', $config['password']);
  341.  
  342.         if(!is_array($from)) {
  343.             $from = [
  344.                 'address' => $from
  345.             ];
  346.         }
  347.  
  348.         Mail::send($view, $data,
  349.             function ($message) use ($to, $from, $subject) {
  350.                 /** @var Message $message */
  351.                 $message->from($from['address'], isset($from['name']) ? $from['name'] : null);
  352.                 //if to is array then loop and add all emails as recipients
  353.                 if (is_array($to)) {
  354.                     foreach ($to as $sendToEmail) {
  355.                         $message->to($sendToEmail);
  356.                     }
  357.                 } else {
  358.                     $message->to($to);
  359.                 }
  360.                 $message->subject($subject);
  361.             });
  362.     }
  363. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement