first commit symfony 6
This commit is contained in:
57
src/Service/MailService.php
Normal file
57
src/Service/MailService.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
use Symfony\Component\Mailer\MailerInterface;
|
||||
use Symfony\Component\Mime\Email;
|
||||
use Symfony\Component\Mime\Address;
|
||||
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
|
||||
|
||||
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 boolean 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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user