email_queue = $email_queue; } /** * Sends all emails in the {@see $email_queue}. * * @param array $inputs `"password": string`: the CLI password * @return null * @throws InvalidInputException if the CLI password is wrong * @throws UnexpectedException if the mailer fails to send an email */ public function handle(array $inputs): mixed { (new RuleSet(["password" => [new EqualsCliSecretRule()]]))->check($inputs); $mailer = $this->create_mailer(); $emails = $this->email_queue->get_queue(); foreach ($emails as $email) { $mailer->Subject = $email["subject"]; $mailer->Body = $email["body"]; try { $mailer->addAddress($email["recipient"]); $mailer->send(); } catch (PHPMailerException $exception) { $mailer->getSMTPInstance()->reset(); throw new UnexpectedException("Failed to send email.", previous: $exception); } $mailer->clearAddresses(); } $this->email_queue->unqueue_emails($emails); return null; } /** * Creates a {@see PHPMailer} to send emails with. * * @throws UnexpectedException if the {@see PHPMailer} could not be created */ private function create_mailer(): PHPMailer { $config = Config::get(); $mailer = new PHPMailer(); $mailer->IsSMTP(); $mailer->CharSet = "UTF-8"; $mailer->SMTPAuth = true; $mailer->SMTPDebug = SMTP::DEBUG_OFF; $mailer->SMTPKeepAlive = true; $mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mailer->Host = $config["mail"]["host"]; $mailer->Port = $config["mail"]["port"]; $mailer->Username = $config["mail"]["username"]; $mailer->Password = $config["mail"]["password"]; try { $mailer->setFrom($config["mail"]["username"], $config["mail"]["from_name"]); } catch (PHPMailerException $exception) { $mailer->smtpClose(); throw new UnexpectedException( "Failed to set 'from' address while processing email queue.", previous: $exception ); } return $mailer; } }