Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send emails from a Symfony2 service class?

Tags:

php

email

symfony

I can use with success the followig code to send emails from the controller:

$message = \Swift_Message::newInstance()
    ->setSubject('Hello Email')
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setBody($this->renderView('HelloBundle:Hello:email.txt.twig', array('name' => $name)))
;
$this->get('mailer')->send($message);

How must i modify the code to use it from a service class?

like image 304
Udan Avatar asked Oct 18 '12 21:10

Udan


2 Answers

Your service has an external dependency, notably the mailer service. You can either inject the service container itself, or inject the mailer service.

If your service only requires the mailer service and nothing else, I would suggest injecting just the mailer service.

Here is how you would configure the DIC to inject the mailer service using a setter:

<service id="my.service" class="Acme\DemoBundle\Service\Hello">
    <call method="setMailer">
        <argument type="service" id="mailer" />
    </call>
</service>

Within your class, write your setter:

class Hello
{
    protected $mailer;

    public function setMailer($mailer)
    {
        $this->mailer = $mailer;
    }

    public function sendEmail()
    {
        $message = \Swift_Message::newInstance()
            ->setSubject('Hello Email')
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setBody($this->renderView('HelloBundle:Hello:email.txt.twig', array('name' => $name)))
        ;
        $this->mailer->send($message);
    }
}

Note: You will have to render your template within your controller and pass to this email function, or inject the templating service and render within your service.

like image 190
noetix Avatar answered Nov 20 '22 18:11

noetix


It depends how you have declared the service. If you are passing whole service container to it you wouldn't need to change anything, otherwise you will need at least mailer and templating service passed to it and called more directly ($this->get('service') will result in fatal error sinc it depends on container)

See also https://stackoverflow.com/a/12905319/258674

like image 42
dev-null-dweller Avatar answered Nov 20 '22 18:11

dev-null-dweller