config = $this->getConfig(); $this->validateConfig(); $this->mg = $this->createClient(); $this->domain = $this->config["domain"]; $this->sender = $this->config["sender"]; } public function getConfig() { return [ "key" => trim((string) Config::get('mailgun_key', '')), "domain" => trim((string) Config::get('mailgun_domain', '')), "sender" => trim((string) Config::get('mailgun_sender', '')), "endpoint" => rtrim(trim((string) Config::get('mailgun_endpoint', self::DEFAULT_ENDPOINT)), '/') ]; } private function validateConfig() { foreach (['key', 'domain', 'sender'] as $name) { if ($this->config[$name] === '') { throw new RuntimeException('Mailgun configuration mailgun_' . $name . ' is empty.'); } } if ($this->config['endpoint'] === '') { $this->config['endpoint'] = self::DEFAULT_ENDPOINT; } } private function createClient() { $factory = new HttpFactory(); $configurator = (new HttpClientConfigurator()) ->setApiKey($this->config['key']) ->setEndpoint($this->config['endpoint']) ->setHttpClient(new GuzzleClient(['timeout' => 15])) ->setUriFactory($factory); return new MailgunService($configurator); } public function send($to, $subject, $text, $file) { $message = [ 'from' => $this->sender, 'to' => $to, 'subject' => $subject, 'html' => $text ]; if (!empty($file)) { $files = is_array($file) ? $file : [$file]; $message['attachment'] = array_map(function ($path) { return ['filePath' => $path]; }, $files); } return $this->mg->messages()->send($this->domain, $message) !== false; } }