简体   繁体   中英

How can I send emails from a Symfony2 service class?

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

$message = \Swift_Message::newInstance()
    ->setSubject('Hello Email')
    ->setFrom('send@example.com')
    ->setTo('recipient@example.com')
    ->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('send@example.com')
            ->setTo('recipient@example.com')
            ->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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM