1
votes

I have a question that it is possible to send email in dev production in symfony in localhost wamp by using gmail. From template I get input value and set in controller. In congig_dev I have those swiftmailer: transport: gmail host: smtp.gmail.com username: '[email protected]' password: '****'

Below I set program from controller->

<?php

namespace PsiutekBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;


class BasketController extends Controller
{
    public function koszykAction()
    {
        return $this->render('PsiutekBundle:Basket:koszyk.html.twig');
    }

    public function SendMailAction()
    {
        $Request=$this->get('request_stack')->getCurrentRequest();
            if($Request->getMethod()=="POST"){

                $subject=$Request->get("Subject");
                print_r($subject);
                exit;
                $email=$Request->get("email");
                $body=$Request->get("message");
                print_r($body);

                $transport=\Swift_SmtpTransport::newInstance('smtp.gmail.com',465,'ssl')
                    ->setUsername('[email protected]')
                    ->setPassword('******');
                $mailer=\Swift_Mailer::newInstance($transport);

                $message = \Swift_Message::newInstance('Web Lead')
                        ->setSubject($subject)
                        ->setTo($email)
                        ->setBody($body);
                $result=$mailer->send($message);
            }


        return $this->render('PsiutekBundle:Basket:koszyk.html.twig');
    }

}
1
not really a duplicate because this is Symfony2 specific question - these answers are notTomasz Madeyski

1 Answers

0
votes

To send email within Symfony you should use mailer service. Since your controller extends Controller you can get it directly from container. So, your action should look like:

public function sendMail()
{
    $mailer = $this->get('mailer'); //getting mailer from container

    $message = \Swift_Message::newInstance('Web Lead')
                        ->setSubject($subject)
                        ->setTo($email)
                        ->setBody($body);

    $result=$mailer->send($message);

}

There is special howto in cookbook covering this topic.

NOTE: consider moving sending email logic (in fact any logic) outside of your controller class.

NOTE 2: I assume you are aware of exit in your method which will terminate method execution.