Initial release
This commit is contained in:
133
src/LeadMailClient.php
Normal file
133
src/LeadMailClient.php
Normal file
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace LeadM\LeadMail;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class LeadMailClient
|
||||
{
|
||||
protected Client $http;
|
||||
|
||||
public function __construct(
|
||||
protected readonly string $baseUrl,
|
||||
protected readonly string $token,
|
||||
protected readonly int $timeout = 30,
|
||||
protected readonly bool $verifySsl = true,
|
||||
protected readonly bool $autoTenant = true,
|
||||
) {
|
||||
$this->http = new Client([
|
||||
'base_uri' => rtrim($this->baseUrl, '/').'/api/v1/',
|
||||
'timeout' => $this->timeout,
|
||||
'verify' => $this->verifySsl,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an email through the leadMail service.
|
||||
*
|
||||
* @param array{from: array, to: array, cc?: array, bcc?: array, reply_to?: array, subject: string, html_body?: string, text_body?: string, attachments?: array, metadata?: array, options?: array} $data
|
||||
* @return array{success: bool, data: array{log_id: int, status: string}}
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function sendEmail(array $data): array
|
||||
{
|
||||
$response = $this->http->post('emails/send', [
|
||||
'headers' => $this->headers(),
|
||||
'json' => $data,
|
||||
]);
|
||||
|
||||
return json_decode($response->getBody()->getContents(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the allowed sender domains for this client app.
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function getDomains(): array
|
||||
{
|
||||
$response = $this->http->get('domains', [
|
||||
'headers' => $this->headers(),
|
||||
]);
|
||||
|
||||
$data = json_decode($response->getBody()->getContents(), true);
|
||||
|
||||
return $data['data']['domains'] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify an email address through the leadMail service.
|
||||
*
|
||||
* @return array{success: bool, data: array{email: string, valid: bool, status: string, reason: ?string, cached: bool}}
|
||||
*/
|
||||
public function verifyEmail(string $email, bool $allowDisposable = false): array
|
||||
{
|
||||
try {
|
||||
$response = $this->http->post('emails/verify', [
|
||||
'headers' => $this->headers(),
|
||||
'json' => [
|
||||
'email' => $email,
|
||||
'allow_disposable' => $allowDisposable,
|
||||
],
|
||||
]);
|
||||
|
||||
return json_decode($response->getBody()->getContents(), true);
|
||||
} catch (GuzzleException $e) {
|
||||
Log::warning('LeadMail verification failed, failing open', [
|
||||
'email' => $email,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'email' => $email,
|
||||
'valid' => true,
|
||||
'status' => 'unknown',
|
||||
'reason' => null,
|
||||
'cached' => false,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function headers(): array
|
||||
{
|
||||
$headers = [
|
||||
'Authorization' => 'Bearer '.$this->token,
|
||||
'Accept' => 'application/json',
|
||||
'Content-Type' => 'application/json',
|
||||
];
|
||||
|
||||
if ($this->autoTenant && $this->hasTenancy()) {
|
||||
$tenantId = $this->resolveTenantId();
|
||||
if ($tenantId !== null) {
|
||||
$headers['X-Tenant-Id'] = $tenantId;
|
||||
}
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
protected function hasTenancy(): bool
|
||||
{
|
||||
return class_exists(\Stancl\Tenancy\Tenancy::class);
|
||||
}
|
||||
|
||||
protected function resolveTenantId(): ?string
|
||||
{
|
||||
if (! function_exists('tenancy') || ! tenancy()->initialized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (string) tenant()->getTenantKey();
|
||||
}
|
||||
}
|
||||
20
src/LeadMailFacade.php
Normal file
20
src/LeadMailFacade.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace LeadM\LeadMail;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
/**
|
||||
* @method static array sendEmail(array $data)
|
||||
* @method static string[] getDomains()
|
||||
* @method static array verifyEmail(string $email, bool $allowDisposable = false)
|
||||
*
|
||||
* @see \LeadM\LeadMail\LeadMailClient
|
||||
*/
|
||||
class LeadMailFacade extends Facade
|
||||
{
|
||||
protected static function getFacadeAccessor(): string
|
||||
{
|
||||
return LeadMailClient::class;
|
||||
}
|
||||
}
|
||||
52
src/LeadMailServiceProvider.php
Normal file
52
src/LeadMailServiceProvider.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace LeadM\LeadMail;
|
||||
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use LeadM\LeadMail\Rules\LeadMailVerify;
|
||||
|
||||
class LeadMailServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__.'/../config/leadmail.php', 'leadmail');
|
||||
|
||||
$this->app->singleton(LeadMailClient::class, function () {
|
||||
return new LeadMailClient(
|
||||
baseUrl: config('leadmail.url'),
|
||||
token: config('leadmail.token', ''),
|
||||
timeout: config('leadmail.timeout', 30),
|
||||
verifySsl: config('leadmail.verify_ssl', true),
|
||||
autoTenant: config('leadmail.auto_tenant', true),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->publishes([
|
||||
__DIR__.'/../config/leadmail.php' => config_path('leadmail.php'),
|
||||
], 'leadmail-config');
|
||||
}
|
||||
|
||||
Mail::extend('leadmail', function () {
|
||||
return new LeadMailTransport(
|
||||
$this->app->make(LeadMailClient::class),
|
||||
);
|
||||
});
|
||||
|
||||
Validator::extend('leadmail_verify', function (string $attribute, mixed $value) {
|
||||
$rule = $this->app->make(LeadMailVerify::class);
|
||||
$passed = true;
|
||||
|
||||
$rule->validate($attribute, $value, function () use (&$passed) {
|
||||
$passed = false;
|
||||
});
|
||||
|
||||
return $passed;
|
||||
}, 'The :attribute email address could not be verified.');
|
||||
}
|
||||
}
|
||||
105
src/LeadMailTransport.php
Normal file
105
src/LeadMailTransport.php
Normal file
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace LeadM\LeadMail;
|
||||
|
||||
use Symfony\Component\Mailer\SentMessage;
|
||||
use Symfony\Component\Mailer\Transport\AbstractTransport;
|
||||
use Symfony\Component\Mime\Address;
|
||||
use Symfony\Component\Mime\Email;
|
||||
use Symfony\Component\Mime\MessageConverter;
|
||||
|
||||
class LeadMailTransport extends AbstractTransport
|
||||
{
|
||||
public function __construct(
|
||||
protected readonly LeadMailClient $client,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function doSend(SentMessage $message): void
|
||||
{
|
||||
$email = MessageConverter::toEmail($message->getOriginalMessage());
|
||||
|
||||
$payload = $this->buildPayload($email);
|
||||
|
||||
$result = $this->client->sendEmail($payload);
|
||||
|
||||
if (isset($result['data']['log_id'])) {
|
||||
$message->getOriginalMessage()->getHeaders()->addTextHeader(
|
||||
'X-LeadMail-Log-Id',
|
||||
(string) $result['data']['log_id'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function buildPayload(Email $email): array
|
||||
{
|
||||
$payload = [
|
||||
'from' => $this->formatAddress($email->getFrom()[0] ?? null),
|
||||
'to' => array_map(fn (Address $a) => $this->formatAddress($a), $email->getTo()),
|
||||
'subject' => $email->getSubject() ?? '',
|
||||
];
|
||||
|
||||
if ($email->getCc()) {
|
||||
$payload['cc'] = array_map(fn (Address $a) => $this->formatAddress($a), $email->getCc());
|
||||
}
|
||||
|
||||
if ($email->getBcc()) {
|
||||
$payload['bcc'] = array_map(fn (Address $a) => $this->formatAddress($a), $email->getBcc());
|
||||
}
|
||||
|
||||
if ($email->getReplyTo()) {
|
||||
$replyTo = $email->getReplyTo()[0];
|
||||
$payload['reply_to'] = $this->formatAddress($replyTo);
|
||||
}
|
||||
|
||||
if ($email->getHtmlBody()) {
|
||||
$payload['html_body'] = $email->getHtmlBody();
|
||||
}
|
||||
|
||||
if ($email->getTextBody()) {
|
||||
$payload['text_body'] = $email->getTextBody();
|
||||
}
|
||||
|
||||
$attachments = [];
|
||||
foreach ($email->getAttachments() as $attachment) {
|
||||
$attachments[] = [
|
||||
'content' => base64_encode($attachment->getBody()),
|
||||
'filename' => $attachment->getFilename() ?? 'attachment',
|
||||
'mime_type' => $attachment->getMediaType().'/'.$attachment->getMediaSubtype(),
|
||||
];
|
||||
}
|
||||
|
||||
if ($attachments) {
|
||||
$payload['attachments'] = $attachments;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{email: string, name?: string}
|
||||
*/
|
||||
protected function formatAddress(?Address $address): array
|
||||
{
|
||||
if ($address === null) {
|
||||
return ['email' => ''];
|
||||
}
|
||||
|
||||
$result = ['email' => $address->getAddress()];
|
||||
|
||||
if ($address->getName()) {
|
||||
$result['name'] = $address->getName();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return 'leadmail';
|
||||
}
|
||||
}
|
||||
35
src/Rules/LeadMailVerify.php
Normal file
35
src/Rules/LeadMailVerify.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace LeadM\LeadMail\Rules;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use LeadM\LeadMail\LeadMailClient;
|
||||
|
||||
class LeadMailVerify implements ValidationRule
|
||||
{
|
||||
public function __construct(
|
||||
protected readonly LeadMailClient $client,
|
||||
protected readonly bool $allowDisposable = false,
|
||||
) {}
|
||||
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
if (! is_string($value) || ! filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
||||
$fail('The :attribute must be a valid email address.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $this->client->verifyEmail($value, $this->allowDisposable);
|
||||
|
||||
if (! ($result['data']['valid'] ?? true)) {
|
||||
$reason = $result['data']['reason'] ?? 'verification failed';
|
||||
$fail("The :attribute email address is not deliverable ({$reason}).");
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Fail open — if the verification service is down, allow the email through
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user