如何从Symfony2服务类发送邮件? [英] How can I send emails from a Symfony2 service class?

查看:105
本文介绍了如何从Symfony2服务类发送邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以成功使用followig代码从控制器发送电子邮件:

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.

以下是如何配置DIC使用setter注入邮件服务:

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.

这篇关于如何从Symfony2服务类发送邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆