2

Does anyone know how you can extend the Mailer class in the FOSUserBundle?

I am implementing a very basic parental email check (all the validation is done on the form to force a parent's email to be entered), if the parent email field is populated on the user entity then it shoudl send the email to that address not the user's email.

I have tried the following so far:

namespace SSERugby\UserBundle\Mailer;

use FOS\UserBundle\Mailer\Mailer as BaseMailer;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\Routing\RouterInterface;

class Mailer extends BaseMailer
{
public function sendConfirmationEmailMessage(UserInterface $user)
{
    $email = $user->getEmail();

    $parentEmail = $user->getParentEmail();

    if(isset($parentEmail)&&(trim($parentEmail)!='')){
        $email = $parentEmail;
    }

    $template = $this->parameters['confirmation.template'];
    $url = $this->router->generate('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), true);
    $rendered = $this->templating->render($template, array(
        'user' => $user,
        'confirmationUrl' =>  $url
    ));
    $this->sendEmailMessage($rendered, $this->parameters['from_email']['confirmation'], $email);
}
}

It seems to just ignore the overridden class though and use the default, i have cleared the cache before testing.

Thanks

chrishey
  • 451
  • 6
  • 11

1 Answers1

5

You should create new service with extended mail class (in src\SSERugby\UserBundle\Resources\config\services.xml) like:

<service id="my_mailer" class="SSERugby\UserBundle\Mailer\Mailer" public="true">
    <argument type="service" id="mailer" />
    <argument type="service" id="router" />
    <argument type="service" id="templating" />
    <argument type="collection">
        <argument key="confirmation.template">%fos_user.registration.confirmation.template%</argument>
        <argument key="resetting.template">%fos_user.resetting.email.template%</argument>
        <argument key="from_email" type="collection">
            <argument key="confirmation">%fos_user.registration.confirmation.from_email%</argument>
            <argument key="resetting">%fos_user.resetting.email.from_email%</argument>
        </argument>
    </argument>
</service>

and then in app/config/config.yml use this service as default:

fos_user:
    # ...
    service:
        mailer: my_mailer

FYI: I copied all service's arguments from FOSUserBundle default mailer config. You can add your own params to it. Also you can read about custom mailers at https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/emails.md

a.tereschenkov
  • 807
  • 4
  • 10