You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Mail/Mailgun.php

84 lines
2.4 KiB
PHTML

<?php
namespace App\Services\Mail;
use App\Services\Config;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory;
use Mailgun\HttpClient\HttpClientConfigurator;
use Mailgun\Mailgun as MailgunService;
use RuntimeException;
class Mailgun extends Base
{
private const DEFAULT_ENDPOINT = 'https://api.mailgun.net';
private $config;
private $mg;
private $domain;
private $sender;
public function __construct()
{
$this->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;
}
}