/** * Queues email message * @param $from * @param $to * @param $subject * @param $text * @param int $priority * @param array $files * @param null $bcc * @return bool */ public function queue($from, $to, $subject, $text, $priority = 0, $files = [], $bcc = null) { if (is_array($bcc)) { $bcc = implode(', ', $bcc); } $model = new Message(); $model->from = $from; $model->to = $to; $model->subject = $subject; $model->text = $text; $model->priority = $priority; $model->files = $files; $model->bcc = $bcc; return $model->save(); }
/** * Send one email from queue * @return bool * @throws \Exception * @throws \yii\db\Exception */ public function sendOne() { $db = \Yii::$app->db; $transaction = $db->beginTransaction(); try { $id = $db->createCommand('SELECT id FROM {{%email_message}} WHERE status=:status ORDER BY priority DESC, id ASC LIMIT 1 FOR UPDATE', ['status' => Message::STATUS_NEW])->queryScalar(); if ($id === false) { $transaction->rollback(); return false; } /** @var Message $model */ $model = Message::findOne($id); $model->status = Message::STATUS_IN_PROGRESS; $model->updateAttributes(['status']); $transaction->commit(); } catch (\Exception $e) { $transaction->rollback(); throw $e; } $transaction = $db->beginTransaction(); try { $result = EmailManager::getInstance()->send($model->from, $model->to, $model->subject, $model->text, $model->files, $model->bcc); if ($result) { $model->sentAt = new Expression('NOW()'); $model->status = Message::STATUS_SENT; } else { $model->status = Message::STATUS_ERROR; } $model->updateAttributes(['sentAt', 'status']); $transaction->commit(); } catch (\Exception $e) { $transaction->rollback(); throw $e; } return true; }