Send email containing login and pass after registration

被刻印的时光 ゝ 提交于 2021-02-19 07:18:48

问题


I am currently working on a Symfony2 project for managing user I installed the bundle FosUserBundle which is functional but I can not find how to send an email containing the username and password immediately after creating user, as I said I have two user: admin and user type, and it is the admin who will create the users with a form of creation that is the form of FOS Registration, changing between the two kind user is only the roles.


回答1:


You could hook into the EventDispatcher and send your own email rather than than the one generated by FOSUserBundle using your own Listener.

class EmailConfirmationListener implements EventSubscriberInterface
{
    private $mailer;
    private $router;
    private $session;

    public function __construct(MailerInterface $mailer,
            UrlGeneratorInterface $router)
    {
        $this->mailer = $mailer;
        $this->router = $router;
    }

    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_SUCCESS => array(
                array('onRegistrationSuccess',  -10),
            ),
        );
    }

    public function onRegistrationSuccess(FormEvent $event)
    {
        /** @var $user \FOS\UserBundle\Model\UserInterface */
        $user = $event->getForm()->getData();

        // send details out to the user
        $this->mailer->sendCreatedUserEmail($user);

        // Your route to show the admin that the user has been created
        $url = $this->router->generate('blah_blah_user_created');
        $event->setResponse(new RedirectResponse($url));

        // Stop the later events propagting
        $event->stopPropagation();
    }
}

Mailer service

use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Mailer\Mailer as BaseMailer;

class Mailer extends BaseMailer
{
    /**
     * @param UserInterface $user
     */
    public function sendAdminConfirmationEmailMessage(UserInterface $user)
    {
        /**
         * Custom template using same positioning as
         * FOSUSerBundle:Registration:email.txt.twig so that the sendEmailMessage
         * method will break it up correctly
         */
        $template = 'BlahBlahUser:Admin:created_user_email.txt.twig';
        $url = $this->router->generate('** custom login path**', array(), true);
        $rendered = $this->templating->render($template, array(
            'user' => $user,
            'password' => $user->getPlainPassword(),
        ));
        $this->sendEmailMessage($rendered,
            $this->parameters['from_email']['confirmation'], $user->getEmail());
    }
}

I think that would do it.. although I could be wrong.




回答2:


It's documented in the bundle's doc:

// src/Acme/UserBundle/Controller/RegistrationController.php
<?php

namespace Acme\UserBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController
{
    public function registerAction()
    {
        $form = $this->container->get('fos_user.registration.form');
        $formHandler = $this->container->get('fos_user.registration.form.handler');
        $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');

        $process = $formHandler->process($confirmationEnabled);
        if ($process) {
            $user = $form->getData();

            /*****************************************************
             * Add new functionality (e.g. log the registration) *
             *****************************************************/
            $this->container->get('logger')->info(
                sprintf('New user registration: %s', $user)
            );

            if ($confirmationEnabled) {
                $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
                $route = 'fos_user_registration_check_email';
            } else {
                $this->authenticateUser($user);
                $route = 'fos_user_registration_confirmed';
            }

            $this->setFlash('fos_user_success', 'registration.flash.user_created');
            $url = $this->container->get('router')->generate($route);

            return new RedirectResponse($url);
        }

        return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
            'form' => $form->createView(),
        ));
    }
}



回答3:


Just use the template and translator

Config

fos_user:
    registration:
       form:
           template:   AppBundle:Registration:email.txt.twig

Template

{% trans_default_domain 'FOSUserBundle' %}
{% block subject %}
{%- autoescape false -%}
{{ 'registration.email.subject'|trans({'%username%': user.username, '%confirmationUrl%': confirmationUrl}) }}
{%- endautoescape -%}
{% endblock %}

{% block body_text %}
{% autoescape false %}
{{ 'registration.email.message'|trans({'%username%': user.username, '%confirmationUrl%': confirmationUrl, %userpassword%: user.plainPassword}) }}
{% endautoescape %}
{% endblock %}
{% block body_html %}{% endblock %}

Translator app\Resources\translations\FOSUserBundle.en.yml

registration:
    check_email: |
        An email has been sent to %email%. It contains an activation link you must click to activate your account.
    confirmed: 'Congrats %username%, your account is now activated.'
    back: 'Back to the originating page.'
    submit: Register
    flash:
        user_created: 'The user has been created successfully.'
    email:
        subject: 'Welcome %username%!'
        message: |
            Hello %username%!

            To finish activating your account - please visit %confirmationUrl%

            User name: %username%
            Password: %userpassword%

            This link can only be used once to validate your account.

            Regards,
            the Team.



回答4:


Here is how to send username/email and password to user after registration using symfony2:

overide email.txt.twig to your own bundle then add this email body :

{% block subject %}
    Welcome to My Application
{% endblock %}

{% block body_html %}
    Email : {{ user.email }} 
    Username : {{ user.username }} 
    Password : {{ user.plainPassword }} 
    Activation Link : {{confirmationUrl}} 
{% endblock %}

then email will be sent to user's email with email, username, password and activation Url to activate account.



来源:https://stackoverflow.com/questions/17742030/send-email-containing-login-and-pass-after-registration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!