发送电子邮件外部控制器操作Symfony2

Muh*_*air 5 symfony fosuserbundle

我正在使用Symfony2和FOSUserBundle

我必须在我的邮件程序类中使用SwiftMailer发送电子邮件,这不是控制器或其操作我正在显示我编码的内容

<?php

namespace Blogger\Util;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class FlockMailer {


    public function SendEmail(){
        $message = \Swift_Message::newInstance()
        ->setSubject('Hello Email')
        ->setFrom('send@example.com')
        ->setTo('to@example.com')
        ->setBody('testing email');

        $this->get('mailer')->send($message);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误

Fatal error: Call to undefined method Blogger\Util\FlockMailer::get() ....
Run Code Online (Sandbox Code Playgroud)

任何身体都可以帮助我这真的很让我感到沮丧.....

gre*_*emo 8

编辑:因为我没有测试代码,如果你不使用服务容器获取邮件程序的实例,你还应该指定传输层.请看: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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要在控制器操作中使用它:

services:
    mail_helper:
        class:     namespace Blogger\Util\MailHelper
        arguments: ['@mailer']

public function sendAction(/* params here */)
{
    $this->get('mail_helper')->sendEmail($from, $to, $body);
}
Run Code Online (Sandbox Code Playgroud)

或者在其他地方没有访问服务容器:

class WhateverClass
{

    public function whateverFunction()
    {
        $helper = new MailerHelper(new \Swift_Mailer);
        $helper->sendEmail($from, $to, $body);
    }

}
Run Code Online (Sandbox Code Playgroud)

或者在访问容器的自定义服务:

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']]
Run Code Online (Sandbox Code Playgroud)


小智 1

忘记 setter 和 getter:

$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$helper = new MailHelper($mailer);
$helper->sendEmail($from, $to, $body,$subject);
Run Code Online (Sandbox Code Playgroud)

这对我来说适用于从侦听器方法调用的 MailHelper。