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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With