2022-07-21 16:15:47 +02:00
|
|
|
<?php
|
2022-09-23 16:14:15 +02:00
|
|
|
|
2022-07-21 16:15:47 +02:00
|
|
|
namespace App\Service;
|
2022-09-23 16:14:15 +02:00
|
|
|
|
|
|
|
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
|
2022-07-21 16:15:47 +02:00
|
|
|
use Symfony\Component\Mailer\MailerInterface;
|
|
|
|
use Symfony\Component\Mime\Address;
|
2022-09-23 16:14:15 +02:00
|
|
|
use Symfony\Component\Mime\Email;
|
2022-07-21 16:15:47 +02:00
|
|
|
|
|
|
|
class MailService
|
|
|
|
{
|
|
|
|
protected $mailer;
|
|
|
|
protected $twig;
|
2022-09-23 16:14:15 +02:00
|
|
|
|
2022-07-21 16:15:47 +02:00
|
|
|
public function __construct(MailerInterface $mailer, \Twig\Environment $twig)
|
|
|
|
{
|
|
|
|
$this->mailer = $mailer;
|
|
|
|
$this->twig = $twig;
|
|
|
|
}
|
2022-09-23 16:14:15 +02:00
|
|
|
|
2022-07-21 16:15:47 +02:00
|
|
|
/**
|
2022-09-23 16:14:15 +02:00
|
|
|
* Send email.
|
2022-07-21 16:15:47 +02:00
|
|
|
*
|
2022-09-23 16:14:15 +02:00
|
|
|
* @param string $template email template
|
|
|
|
* @param mixed $parameters custom params for template
|
|
|
|
* @param string $to to email address or array of email addresses
|
|
|
|
* @param string $from from email address
|
|
|
|
* @param string $fromName from name
|
2022-07-21 16:15:47 +02:00
|
|
|
*
|
2022-09-23 16:14:15 +02:00
|
|
|
* @return bool send status
|
2022-07-21 16:15:47 +02:00
|
|
|
*/
|
|
|
|
public function sendEmail($subject, $body, $to, $from, $fromName = null)
|
|
|
|
{
|
|
|
|
$template = $this->twig->load('Home/mail.html.twig');
|
2022-09-23 16:14:15 +02:00
|
|
|
|
|
|
|
$parameters = ['subject' => $subject, 'body' => $body];
|
|
|
|
$subject = $template->renderBlock('subject', $parameters);
|
2022-07-21 16:15:47 +02:00
|
|
|
$bodyHtml = $template->renderBlock('body', $parameters);
|
2022-09-23 16:14:15 +02:00
|
|
|
|
2022-07-21 16:15:47 +02:00
|
|
|
try {
|
2022-09-23 16:14:15 +02:00
|
|
|
if (!is_array($to)) {
|
|
|
|
$to = [$to];
|
|
|
|
}
|
2022-07-21 16:15:47 +02:00
|
|
|
|
2022-09-23 16:14:15 +02:00
|
|
|
foreach ($to as $t) {
|
2022-07-21 16:15:47 +02:00
|
|
|
$message = (new Email())
|
|
|
|
->subject($subject)
|
2022-09-23 16:14:15 +02:00
|
|
|
->from(Address::create($fromName.'<'.$from.'>'))
|
2022-07-21 16:15:47 +02:00
|
|
|
->to($t)
|
|
|
|
->html($bodyHtml);
|
|
|
|
$this->mailer->send($message);
|
|
|
|
}
|
|
|
|
} catch (TransportExceptionInterface $e) {
|
|
|
|
return $e->getMessage();
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2022-09-23 16:14:15 +02:00
|
|
|
}
|