maxPerBatch = config('mail.queue.emails_per_batch'); $this->numberOfAttempts = config('mail.queue.max_attempts'); $this->secondsBetweenPolls = config('mail.queue.seconds_between_polls'); } /** * Execute the console command. * * @return mixed */ public function handle() { if (!UserConfig::get('queue_emails')) { $this->output->error('E-mail queueing is not enabled. E-mails are being sent immediately.'); } $this->output->writeln('Setting mail configuration'); GlobalConfiguration::updateMailConfig(); $this->output->writeln('E-mail queue runner started'); while (true) { $emailsToSend = EmailLog::where([ ['sent_at', null], ['number_attempts', '<', $this->numberOfAttempts] ])->limit($this->maxPerBatch)->get(); $this->output->writeln(sprintf( '%d e-mail%s to send', $emailsToSend->count(), $emailsToSend->count() == 1 ? '' : 's' )); /** @var EmailLog $emailToSend */ foreach ($emailsToSend as $emailToSend) { $this->sendEmail($emailToSend); } if (!$this->option('poll')) { exit(); } sleep($this->secondsBetweenPolls); } } private function sendEmail(EmailLog $emailLog) { $this->output->writeln(sprintf('Sending message with subject \'%s\'', $emailLog->subject)); try { app('mailer')->send( [], [], function (Message $message) use ($emailLog) { $message->setFrom($emailLog->sender_address, $emailLog->sender_name); $message->setSubject($emailLog->subject); $this->addAddresses($emailLog->to_addresses, $message, 'To'); $this->addAddresses($emailLog->cc_addresses, $message, 'Cc'); $this->addAddresses($emailLog->bcc_addresses, $message, 'Bcc'); $message->addPart($emailLog->body_plain, 'text/plain'); $message->setBody($emailLog->body_html, 'text/html'); } ); $emailLog->sent_at = new \DateTime(); $this->output->writeln('Send completed'); } catch (\Exception $ex) { $this->output->error(sprintf('Send failed: %s', $ex->getMessage())); } finally { $emailLog->number_attempts++; $emailLog->save(); } } private function addAddresses($dbFieldData, Message $message, $property) { $decoded = json_decode($dbFieldData); if (is_array($decoded)) { foreach ($decoded as $addressInfo) { $this->output->writeln(sprintf('Adding %s address: \'"%s" <%s>\'', $property, $addressInfo->name, $addressInfo->address)); $message->{"set{$property}"}($addressInfo->address, $addressInfo->name); } } } }