編輯:因爲我沒有測試過代碼,所以如果你不使用服務容器來獲取郵件的實例,你還應該指定傳輸層。看看: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']]
我不明白。該代碼片段是否意味着您當前的解決方案,但您想將郵件移動到其他位置?如果這是正確的,你應該閱讀有關注入服務到你的自定義類:http://stackoverflow.com/questions/6124444/how-can-i-access-a-service-outside-of-a-controller-with- symfony2 – geca 2012-04-20 13:09:18
我已經使用FOSUserBundle和FOSFacebookbundle我想要什麼時,用戶成功登錄Facebook帳戶時,我想用他的密碼發送電子郵件給用戶,以便他可以使用該電子郵件密碼登錄,因爲我必須在提供者類中編寫函數以發送電子郵件... – 2012-04-20 13:17:17