编辑:因为我没有测试代码,如果您不使用服务容器来获取邮件程序的实例,您还应该指定传输层。看:http ://swiftmailer.org/docs/sending.html
你这样做是错的。你基本上想要一个服务,而不是一个扩展的类Controller
。它不起作用,因为服务容器在SendMail()
功能中不可用。
您必须将服务容器注入您自己的自定义助手中才能发送电子邮件。几个例子:
namespace Blogger\Util;
class MailHelper
{
protected $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function sendEmail($from, $to, $body, $subject = '')
{
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($from)
->setTo($to)
->setBody($body);
$this->mailer->send($message);
}
}
要在控制器操作中使用它:
services:
mail_helper:
class: namespace Blogger\Util\MailHelper
arguments: ['@mailer']
public function sendAction(/* params here */)
{
$this->get('mail_helper')->sendEmail($from, $to, $body);
}
或其他地方不访问服务容器:
class WhateverClass
{
public function whateverFunction()
{
$helper = new MailerHelper(new \Swift_Mailer);
$helper->sendEmail($from, $to, $body);
}
}
或者在访问容器的自定义服务中:
namespace Acme\HelloBundle\Service;
class MyService
{
protected $container;
public function setContainer($container) { $this->container = $container; }
public function aFunction()
{
$helper = $this->container->get('mail_helper');
// Send email
}
}
services:
my_service:
class: namespace Acme\HelloBundle\Service\MyService
calls:
- [setContainer, ['@service_container']]