feat: integrate with MailJet API for newsletter registration

This commit is contained in:
Björn Fromme
2026-03-19 09:42:00 +01:00
parent 66c55f0722
commit d1e2bf3e7d
26 changed files with 1537 additions and 47 deletions
+99
View File
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace App\Email;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\BodyRendererInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class Mailer
{
public function __construct(
private readonly MailerInterface $mailer,
private readonly BodyRendererInterface $bodyRenderer,
private readonly LoggerInterface $logger,
private readonly array $defaults,
) {
}
public function createAndSendEmail(array $context, array $options): void
{
$config = $this->resolveConfig($options);
$email = $this->create($context, $config);
$recipients = (array) $config['to'];
foreach ($recipients as $recipient) {
$email->to($recipient);
$this->send($email);
}
}
public function create(array $context, array $config): TemplatedEmail
{
$email = (new TemplatedEmail())
->from($config['from'])
->subject($config['subject'])
->htmlTemplate($config['template'])
->context($context)
;
foreach ($config['attachments'] as $attachment) {
/* @var EmailAttachmentInterface $attachment */
$attachment->attachTo($email);
}
$this->bodyRenderer->render($email);
return $email;
}
public function send(TemplatedEmail $email): void
{
$recipients = array_map(fn (Address $address) => $address->toString(), $email->getTo());
try {
$this->mailer->send($email);
$this->logger->info('Send email', [
'to' => $recipients,
'subject' => $email->getSubject(),
]);
} catch (TransportExceptionInterface $e) {
$this->logger->error('Email could not be sent', [
'to' => $recipients,
'subject' => $email->getSubject(),
'error' => $e->getMessage(),
]);
}
}
private function resolveConfig(array $options): array
{
$resolver = new OptionsResolver();
$resolver
->setDefaults([
'from' => $this->defaults['from'],
'to' => $this->defaults['to'],
'subject_parameters' => [],
'attachments' => [],
])
->setRequired([
'template',
'subject',
])
->setAllowedTypes('to', ['string', 'array'])
->setAllowedTypes('template', 'string')
->setAllowedTypes('subject', 'string')
->setAllowedTypes('attachments', 'array')
;
return $resolver->resolve($options);
}
}