简体   繁体   中英

Swift mailer won't send emails

I have a form which is only for admins. Admins can add users with a default password 1234. I also would like to send an email to the added user after the successful creation. Everything works fine in the controller except the swift mailer part. After sending the form debug bar doesn't show any emails as sent. If I put that part out of the if statement, it works fine and I can see the email in the debug bar. However all the other parts that are in if statement works just fine.

Here is my method;

 /**
 * @Route("/add-user", name="adduser")
 */
public function addUserAction(Request $request){
    $user = new User();
    $addform = $this->createForm(NewUserType::class,$user);
    $addform->handleRequest($request);
    if ($addform->isSubmitted() && $addform->isValid()) {
        $user->setRoles(array('ROLE_USER'));
        $password = $this->get('security.password_encoder')
            ->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($password);
        $cellphone = $addform->get('cellphone')->getData();
        $ccode = $addform->get('ccode')->getData();
        $cellphone =  preg_replace("/[^0-9A-Za-z]/", "", $cellphone);
        $user->setCcode($ccode);
        $user->setCellphone($cellphone);
        $user->setPlainPassword(1234);
        $user->setPassword(md5(1234));
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        $this->addFlash(
            'addeduser',
            'You successfully added a user to the database'
        );

        $emailMessage = \Swift_Message::newInstance()
            ->setSubject('You have successfully signed up')
            ->setFrom('info@kampapp.com')
            ->setTo($user->getUsername())
            ->setBody($this->renderView(':emails:addeduser.html.twig'));
        $this->get('mailer')->send($emailMessage);

        return $this->redirect($this->generateUrl('adduser'));

    }

    else{
            $this->addFlash(
                'addusererror',
                'Oops! There was an error!'
            );
        }

    return $this->render(':user:adduser.html.twig', array('addform'=>$addform->createView()));
    }

If you're sending an email and then immediately redirecting to another page ( which is your case ), the web debug toolbar will not display an email icon or a report on the next page.

Instead, you can set the intercept_redirects option to true in the config_dev.yml file, which will cause the redirect to stop and allow you to open the report with details of the sent emails.

# app/config/config_dev.yml
web_profiler:
    intercept_redirects: true

See more in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM