nineskeletor/src/Service/MailService.php

60 lines
1.7 KiB
PHP
Executable File

<?php
namespace App\Service;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
class MailService
{
protected $mailer;
protected $twig;
public function __construct(MailerInterface $mailer, \Twig\Environment $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}
/**
* Send email.
*
* @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
*
* @return bool send status
*/
public function sendEmail($subject, $body, $to, $from, $fromName = null)
{
$template = $this->twig->load('Home/mail.html.twig');
$parameters = ['subject' => $subject, 'body' => $body];
$subject = $template->renderBlock('subject', $parameters);
$bodyHtml = $template->renderBlock('body', $parameters);
try {
if (!is_array($to)) {
$to = [$to];
}
foreach ($to as $t) {
$message = (new Email())
->subject($subject)
->from(Address::create($fromName.'<'.$from.'>'))
->to($t)
->html($bodyHtml);
$this->mailer->send($message);
}
} catch (TransportExceptionInterface $e) {
return $e->getMessage();
}
return true;
}
}