Mailer.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /*
  3. * This file is part of the FOSUserBundle package.
  4. *
  5. * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace FOS\UserBundle\Mailer;
  11. use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
  12. use Symfony\Component\Routing\RouterInterface;
  13. use FOS\UserBundle\Model\UserInterface;
  14. use FOS\UserBundle\Mailer\MailerInterface;
  15. /**
  16. * @author Thibault Duplessis <thibault.duplessis@gmail.com>
  17. */
  18. class Mailer implements MailerInterface
  19. {
  20. protected $mailer;
  21. protected $router;
  22. protected $templating;
  23. protected $parameters;
  24. public function __construct($mailer, RouterInterface $router, EngineInterface $templating, array $parameters)
  25. {
  26. $this->mailer = $mailer;
  27. $this->router = $router;
  28. $this->templating = $templating;
  29. $this->parameters = $parameters;
  30. }
  31. public function sendConfirmationEmailMessage(UserInterface $user)
  32. {
  33. $template = $this->parameters['confirmation.template'];
  34. $url = $this->router->generate('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), true);
  35. $rendered = $this->templating->render($template, array(
  36. 'user' => $user,
  37. 'confirmationUrl' => $url
  38. ));
  39. $this->sendEmailMessage($rendered, $this->parameters['from_email']['confirmation'], $user->getEmail());
  40. }
  41. public function sendResettingEmailMessage(UserInterface $user)
  42. {
  43. $template = $this->parameters['resetting.template'];
  44. $url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()), true);
  45. $rendered = $this->templating->render($template, array(
  46. 'user' => $user,
  47. 'confirmationUrl' => $url
  48. ));
  49. $this->sendEmailMessage($rendered, $this->parameters['from_email']['resetting'], $user->getEmail());
  50. }
  51. /**
  52. * @param string $renderedTemplate
  53. * @param string $toEmail
  54. */
  55. protected function sendEmailMessage($renderedTemplate, $fromEmail, $toEmail)
  56. {
  57. // Render the email, use the first line as the subject, and the rest as the body
  58. $renderedLines = explode("\n", trim($renderedTemplate));
  59. $subject = $renderedLines[0];
  60. $body = implode("\n", array_slice($renderedLines, 1));
  61. $message = \Swift_Message::newInstance()
  62. ->setSubject($subject)
  63. ->setFrom($fromEmail)
  64. ->setTo($toEmail)
  65. ->setBody($body);
  66. $this->mailer->send($message);
  67. }
  68. }