<?php
namespace App\Controller;
use App\Entity\Contact;
use App\Form\ContactType;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class ContactController extends AbstractController
{
#[Route('/contact', name: 'app_contact')]
public function index(Request $request, EntityManagerInterface $em, MailerInterface $mailer): Response
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$contact->setCreatedAt(new \DateTime());
$em->persist($contact);
$em->flush();
$fd = $form->getData();
$notification = (new TemplatedEmail())
->from(new Address('notification@kalsyma-web.fr', 'Notification de nouveau message'))
->to(new Address('kalsyma.web@gmail.com', 'Kalsyma-web'))
//->cc('cc@example.com')
->bcc(new Address('l.p.kaffin@gmail.com', 'notification'))
//->replyTo('fabien@example.com')
->priority(Email::PRIORITY_HIGH)
->subject('Nouveau message')
->htmlTemplate('emails/notification.html.twig')
->context([
'name' => $fd->getName(),
'telephone' => $fd->getTelephone(),
'sender' => $fd->getEmail(),
'message' => $fd->getMessage(),
'sendingDate' => $fd->getCreatedAt(),
]);
try {
$mailer->send($notification);
$this->addFlash('success', "Votre message a bien été envoyé, nous vous recontacterons dès que possible");
return $this->redirectToRoute('app_contact');
} catch (TransportExceptionInterface $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
$this->addFlash('error', 'erreur lors de l\'envoi du mail' . $e);
}
}
return $this->render('contact/index.html.twig', [
'form' => $form->createView(),
]);
}
}