简体   繁体   English

在symfony 2中创建邮件服务

[英]creating a mailer service in symfony 2

I'm very new to Symfony and now I have a question about configuring and sending a mail. 我是Symfony的新手,现在有一个有关配置和发送邮件的问题。 Actually I'm configuring and sending the mail in the controller, but for me it would be better to configure the mail not in the controller, but in an .ini-file or something else. 实际上,我正在控制器中配置和发送邮件,但对我而言,最好不在控制器中而是在.ini文件或其他内容中配置邮件。 Therefore I thought the right way would be to configure it as a service, because so I can configure the mail itself in a class and not in the code. 因此,我认为正确的方法是将其配置为服务,因为这样我可以在类而不是代码中配置邮件本身。

I created a class, that looks like that: 我创建了一个类,如下所示:

class PwMailer{
protected $mailer;

public function setMailer($mailer)
{
    $this->mailer = $mailer;
}

public function sendEmail($email, $password)
{
    $message = \Swift_Message::newInstance()
        ->setSubject('New Password')
        ->setFrom('xxx@nobody.com')
        ->setTo($email)
        ->setBody('Your new Password is '.$password)
    ;
    $this->mailer->send($message);
}

} }

The values $email and $password should come from the controller. 值$ email和$ password应该来自控制器。 In my config-file app\\config\\config.yml I configured it: 在我的配置文件app \\ config \\ config.yml中,我对其进行了配置:

services:
  pw_mailer:
    class:     Pso\LogBundle\PwMailer
    arguments: [sendmail] 

I call the service from controller 我从控制器打电话给服务

$mailer = new Mailer('pw_mailer');
$mailer->send();

Now I got the error "FatalErrorException: Error: Class '...Mailer' not found in '...controller' 现在我得到了错误“ FatalErrorException:错误:在'... controller'中找不到类'... Mailer'

My code is a Mix from http://symfony.com/doc/current/book/service_container.html and How can I send emails from a Symfony2 service class? 我的代码是http://symfony.com/doc/current/book/service_container.html中的Mix,我该如何从Symfony2服务类发送电子邮件?

I would be glad about a hint, if a service container for configuring the mail in a class and not in the controller is the right way and where my mistake in thinking is. 如果有一个提示消息是正确的方式,并且是我思考的错误所在,那么我会很高兴得到提示,如果该服务容器用于在类中而不是在控制器中配置邮件。 Until now I didn't unterstand how the configuration of a service container exactly works. 到目前为止,我还不了解服务容器的配置是如何工作的。

Greetings 问候

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: 这是将DIC配置为使用设置器注入邮件服务的方式:

services:
    pw_mailer:
        class:     Pso\LogBundle\PwMailer
        arguments: [mailer]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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