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.
89 lines
2.6 KiB
PHP
89 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Mail;
|
|
|
|
use App\Services\Config;
|
|
use App\Services\MailSenderIdentity;
|
|
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"];
|
|
try {
|
|
$this->sender = MailSenderIdentity::header($this->config["sender"]);
|
|
} catch (\InvalidArgumentException $exception) {
|
|
throw new RuntimeException('Mailgun configuration mailgun_sender must contain a valid email address.', 0, $exception);
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|