EDIT: as i din't tested the code you should also specify the transport layer if you don't use the service container for getting the instance of the mailer. Look at: http://swiftmailer.org/docs/sending.html
You're doing it wrong. You basically want a service, not a class that extends Controller
. It's not working because service container is not available in SendMail()
function.
You have to inject the service container into your own custom helper for sending email. A few examples:
namespace Blogger\Util;
class MailHelper
{
protected $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function sendEmail($from, $to, $body, $subject = '')
{
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($from)
->setTo($to)
->setBody($body);
$this->mailer->send($message);
}
}
To use it in a controller action:
services:
mail_helper:
class: namespace Blogger\Util\MailHelper
arguments: ['@mailer']
public function sendAction(/* params here */)
{
$this->get('mail_helper')->sendEmail($from, $to, $body);
}
Or elsewhere without accessing the service container:
class WhateverClass
{
public function whateverFunction()
{
$helper = new MailerHelper(new \Swift_Mailer);
$helper->sendEmail($from, $to, $body);
}
}
Or in a custom service accessing the container:
namespace Acme\HelloBundle\Service;
class MyService
{
protected $container;
public function setContainer($container) { $this->container = $container; }
public function aFunction()
{
$helper = $this->container->get('mail_helper');
// Send email
}
}
services:
my_service:
class: namespace Acme\HelloBundle\Service\MyService
calls:
- [setContainer, ['@service_container']]