email - Symfony2 - 如何在 Controller 中调用 Swiftmailer 服务

标签 email symfony service controller swiftmailer

我仍在学习如何将 Swiftmailer 设置为服务,我相信我有一个可行的解决方案,但需要一些关于如何在 Controller 中调用它的帮助。

如何在我的 Controller 中调用此服务?(服务代码,service之前的原始代码以及下面的service.yml)

编辑: 我试图这样调用它:

$emailManager = $this->container->get('email_manager');

$content = $emailManager->sendMail($subject, $recipientName, $recipientEmail, $bodyHtml, $bodyText);

但是我收到了 undefined variable 错误:

注意: undefined variable :/.../DefaultController.php 第 58 行中的主题

电子邮件管理器服务

namespace Acme\EmailBundle\Service;

use Symfony\Component\HttpFoundation\RequestStack;


class EmailManager
{
private $request;
private $mailer;

public function __construct(RequestStack $requestStack, \Swift_Mailer $mailer)
{
    $this->request = $requestStack->getCurrentRequest();
    $this->mailer  = $mailer;
}

public function sendMail($subject, $recipientName, $recipientEmail, $bodyHtml, $bodyText)
{
    /* @var $mailer \Swift_Mailer */
    if(!$this->mailer->getTransport()->isStarted()){
        $this->mailer->getTransport()->start();
    }

    /* @var $message \Swift_Message */
    $message = $this->mailer->createMessage();
    $message->setSubject($subject);

    $message->setBody($bodyHtml, 'text/html');
    $message->addPart($bodyText, 'text/plain', 'UTF8');

    $message->addTo($recipientEmail, $recipientName);
    $message->setFrom( array('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee8b968f839e828bae89838f8782c08d8183" rel="noreferrer noopener nofollow">[email protected]</a>' => 'Chance') );

    $this->mailer->send($message);
    $this->mailer->getTransport()->stop();
}
}

用于在将其作为服务放入之前发送电子邮件的原始 Controller 代码

/**
 * @Route("/", name="contact")
 * @Template("AcmeEmailBundle:Default:index.html.twig")
 */
public function contactAction(Request $request)
{
$form = $this->createForm(new ContactType());

if ($request->isMethod('POST')) {
    $form->submit($request);

    if ($form->isValid()) {
        $message = \Swift_Message::newInstance()
            ->setSubject($form->get('subject')->getData())
            ->setFrom($form->get('email')->getData())
            ->setTo('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781d00191508141d381f15191114561b1715" rel="noreferrer noopener nofollow">[email protected]</a>')
            ->setBody(
                $this->renderView(
                    'AcmeEmailBundle:Default:index.html.twig',
                    array(
                        'ip' => $request->getClientIp(),
                        'name' => $form->get('name')->getData(),
                        'message' => $form->get('message')->getData()
                    )
                )
            );

        $this->get('mailer')->send($message);

        $request->getSession()->getFlashBag()->add('success', 'Your email has been sent! Thanks!');

        return $this->redirect($this->generateUrl('contact'));
    }
}

return array(
    'form' => $form->createView()
);
}

services.yml

services:
email_manager:
    class: Acme\EmailBundle\Service\EmailManager
    arguments: [@request_stack, @mailer]
    scope: request

最佳答案

当你的 Controller 像这样扩展 Controller 时

<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

//...

/**
 * DemoController
 */
class DemoController extends Controller
{
    // ...

}

您可以像这样访问服务:

$emailManager = $this->container->get('email_manager');

然后您可以像这样发送电子邮件:

$emailManager->sendEmail($subject, $recipientName, $recipientEmail, $bodyHtml, $bodyText);

完整概述

1 创建一个电子邮件管理器来撰写并发送电子邮件

<?php

namespace Acme\EmailBundle\Manager;

//...

/**
 * Composes and Sends emails
 */
class EmailManager 
{
    /**
     * The mailer
     *
     * @var \Swift_Mailer
     */
    protected $mailer;

    /**
     * The email address the mailer will send the emails from
     *
     * @var String
     */
    protected $emailFrom;


    /**
     * @param Request $mailer;
     */
    public function __construct(\Swift_Mailer $mailer, $emailFrom)
    {
        $this->mailer = $mailer;
        $this->emailFrom = $emailFrom;
    }

    /**
     * Compose email
     *
     * @param String $subject
     * @param String $recipientEmail
     * @param String $bodyHtml
     * @return \Swift_Message
     */
    public function composeEmail($subject, $recipientEmail, $bodyHtml)
    {
        /* @var $message \Swift_Message */
        $message = $this->mailer->createMessage();

        $message->setSubject($subject)
                ->setBody($bodyHtml, 'text/html')
                ->setTo($recipientEmail)
                ->setFrom($this->emailFrom);

        return $message;
    }


    /**
     * Send email
     *
     * @param \Swift_Message $message;
     */
    public function sendEmail(\Swift_Message $message)
    {
        if(!$this->mailer->getTransport()->isStarted()){
            $this->mailer->getTransport()->start();
        }

        $this->mailer->send($message);
        $this->mailer->getTransport()->stop();
    }


}

3 将其声明为服务

parameters:
    acme_email.email_from: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="107568717d607c7550777d71797c3e737f7d" rel="noreferrer noopener nofollow">[email protected]</a>

services:
    email_manager:
        class: Acme\EmailBundle\Service\EmailManager
        arguments: [@mailer,%acme_email.email_from%]

]

4 创建一个表单处理程序来处理您的联系表单

<?php

namespace Acme\ContactBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Acme\EmailBundle\Manager\EmailManager;

/**
 * Handles Contact forms
 */
class ContactFormHandler
{

    /**
     * The request
     *
     * @var Symfony\Component\HttpFoundation\Request;
     */
    protected $request;

    /**
     * The Template Engine
     */
    protected $templating;

    /**
     * The email manager
     */
    protected $emailManager;

    /**
     * @param Request $request;
     * @param TwigEngine $templating
     * @param EmailManager $emailManager
     */
    public function __construct(Request $request, TwigEngine $templating, EmailManager $emailManager)
    {
        $this->request = $request;
        $this->templating =$templating;
        $this->emailManager = $emailManager;

    }

    /**
     * Processes the form with the request
     *
     * @param Form $form
     * @return Email|false 
     */
    public function process(Form $form)
    {
        if ('POST' !== $this->request->getMethod()) {
            return false;
        }

        $form->bind($this->request);

        if ($form->isValid()) {
            return $this->processValidForm($form);
        }

        return false;
    }

    /**
     * Processes the valid form, sends the email
     *
     * @param Form
     * @return EmailInterface The email sent
     */
    public function processValidForm(Form $form)
    {
        /** @var EmailInterface */
        $email = $this->composeEmail($form);

        /** Send Email */
        $this->emailManager->sendEmail($email);

        return $email;
    }

    /**
     * Composes the email from the form
     *
     * @param Form $form
     * @return \Swift_Message
     */
    public function composeEmail(Form $form)
    {
        $subject = $form->get('subject')->getData();
        $recipientEmail = $form->get('email')->getData();
        $bodyHTML = $this->templating->renderView(
                    'AcmeEmailBundle:Default:index.html.twig',
                    array(
                        'ip' => $this->request->getClientIp(),
                        'name' => $form->get('name')->getData(),
                        'message' => $form->get('message')->getData()
                    )
                );                

        /** @var \Swift_Message */
        return $this->emailManager->composeEmail($subject, $recipientEmail, $bodyHTML);
    }

}

3 将其声明为服务:

services:
    acme_contact.contact_form_handler:
        class:     Acme\ContactBundle\FormHandler\ContactFormHandler
        arguments: [@request, @templating, @email_manager]
        scope: request

4 这让你的 Controller 变得简短而甜蜜

/**
 * @Route("/", name="contact")
 * @Template("AcmeContactBundle:Default:index.html.twig")
 */
public function contactAction(Request $request)
{
    /** BTW, you could create a service to create the form too... */
    $form = $this->createForm(new ContactType());
    $formHandler = $this->container->get('acme_contact.contact_form_handler');

    if ($email = $formHandler->process($form)) {
         $this->setFlash('success', 'Your email has been sent! Thanks!');
         return $this->redirect($this->generateUrl('contact'));
     }

}

关于email - Symfony2 - 如何在 Controller 中调用 Swiftmailer 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539542/

相关文章:

python - 我应该在 python 游戏服务器中使用什么方法来保持滴答时间?

安卓 Facebook 图谱 API JSONException 'No value for email'

Python:解析带有嵌入图像的电子邮件

ruby-on-rails - Sendgrid 上的 Heroku 错误

android - 显示电子邮件 Intent 中预填的收件人地址?

symfony2 CSRF 无效

php - 难以使用 payum Bundle 管理数据

windows - 调试 "service failed to start"Windows Installer 错误

android - 简历上的服务状态

Symfony2预定义参数