1

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: 'ringleaderr@gmail.com' 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('ringleaderr@gmail.com')
                    ->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');
    }

}
  • possible duplicate of [WAMP send Mail using SMTP localhost](http://stackoverflow.com/questions/16830673/wamp-send-mail-using-smtp-localhost) or [How to configure WAMP (localhost) to send email using Gmail?](http://stackoverflow.com/questions/600725/how-to-configure-wamp-localhost-to-send-email-using-gmail) – Veve May 08 '15 at 13:35
  • not really a duplicate because this is ``Symfony2`` specific question - these answers are not – Tomasz Madeyski May 08 '15 at 15:00

1 Answers1

0

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.

Tomasz Madeyski
  • 10,742
  • 3
  • 50
  • 62