Advertisement
Guest User

Untitled

a guest
May 27th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.07 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Console\Commands;
  4.  
  5. use App\Modules\Email\Services\EmailSenderService;
  6. use App\Modules\Email\Models\Email;
  7. use Illuminate\Console\Command;
  8. use Exception;
  9.  
  10. class SendEmail extends Command
  11. {
  12.     /**
  13.      * The name and signature of the console command.
  14.      *
  15.      * @var string
  16.      */
  17.     protected $signature = 'email:send {--limit=100 : Number of emails}';
  18.  
  19.     /**
  20.      * The console command description.
  21.      *
  22.      * @var string
  23.      */
  24.     protected $description = 'Will send all (not sent) outgoing emails';
  25.  
  26.     /**
  27.      * @var EmailSenderService
  28.      */
  29.     private $service;
  30.  
  31.     /**
  32.      * Create a new command instance.
  33.      *
  34.      * @param EmailSenderService $service
  35.      */
  36.     public function __construct(EmailSenderService $service) {
  37.         parent::__construct();
  38.         $this->service = $service;
  39.     }
  40.  
  41.     /**
  42.      * Execute the console command.
  43.      *
  44.      * @return mixed
  45.      */
  46.     public function handle()
  47.     {
  48.         $limit = $this->option('limit');
  49.  
  50.         $query = new Email;
  51.         $query = $query->where('is_sent', 0)->where('direction', Email::DIRECTION_OUT);
  52.  
  53.         if ($limit) {
  54.             $query = $query->limit($limit);
  55.         }
  56.  
  57.         $emails = $query->get();
  58.  
  59.         foreach ($emails as $email) {
  60.             try {
  61.                 $wasSent = $this->service->sendAdvancedEmail(
  62.                     $email->getToEmail(),
  63.                     $email->getFromEmail(),
  64.                     $email->getCcEmail(),
  65.                     $email->getBcc(),
  66.                     $email->getSubject(),
  67.                     $email->getBodyAny()
  68.                 );
  69.  
  70.                 if ($wasSent) {
  71.                     $email->markAsSent();
  72.                     $email->save();
  73.                     $this->line('Email '.$email->getId().' was sent to '.$email->getToEmail());
  74.                 }
  75.  
  76.             } catch (Exception $e) {
  77.                 $this->error('Error while sending email: '.$email->getId());
  78.                 $this->error($e->getMessage());
  79.             }
  80.         }
  81.  
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement