Search code examples
symfonyfosuserbundle

Send email outside Controller Action in Symfony2


I am using Symfony2 and FOSUserBundle

I have to send email using SwiftMailer in my mailer class which is not a controller or its action. I am showing what I have coded

<?php

namespace Blogger\Util;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FlockMailer {


    public function SendEmail(){
        $message = \Swift_Message::newInstance()
        ->setSubject('Hello Email')
        ->setFrom('send@example.com')
        ->setTo('to@example.com')
        ->setBody('testing email');

        $this->get('mailer')->send($message);
    }
}

But I am getting the following error

Fatal error: Call to undefined method Blogger\Util\FlockMailer::get() ....

How can I proceed?


Solution

  • Just forget about the setter and the getter:

    $transport = \Swift_MailTransport::newInstance();
    $mailer = \Swift_Mailer::newInstance($transport);
    $helper = new MailHelper($mailer);
    $helper->sendEmail($from, $to, $body,$subject);
    

    That worked for me with the MailHelper called from a listener method.