FOS UserBundle如何将图像添加到注册电子邮件树枝

时间:2015-01-21 13:23:03

标签: email symfony twig fosuserbundle

如何使用FOS UserBundle在电子邮件树枝中添加公司日志?我确实想在twig文件中使用它,并且不想创建自定义邮件程序类只是为了添加图像。

我已完成覆盖defaild模板并启用快速邮件程序。

到目前为止尝试过:

<img id="logo" src="{{ asset('bundles/demo/img/logo_login.png') }}" alt="test!" />

这会发送电子邮件,但图片路径不完整(缺少主机部分)

当我添加app.request.getSchemeAndHttpHost()以获取主机时,邮件将不会被发送

<img id="logo" src="{{ app.request.getSchemeAndHttpHost() ~ asset('bundles/demo/img/logo_login.png') }}" alt="test!" />

有没有人有我可以尝试的解决方案或想法?

提前致谢

2 个答案:

答案 0 :(得分:1)

asset()会为您网站上的图片创建一个网址。这将使很多垃圾邮件过滤器响起警报,大多数电子邮件客户端只会阻止图像。幸运的是,您可以使用Swiftmailer嵌入图像。

我假设您已按照Sending HTML mails中的说明配置了自定义电子邮件模板。

首先,在您的自定义用户捆绑中创建一个类(当您有overwritten FosUserBundle时)或在其他地方创建一个类,例如Foo/BarBundle/Mailer/CustomUserMailer.php

namespace Foo\BarBundle\Mailer;

use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class CustomUserMailer extends BaseMailer
{
    public function __construct(
        \Swift_Mailer $mailer,
        UrlGeneratorInterface $router,
        \Twig_Environment $twig,
        array $parameters
    )
    {
        parent::__construct($mailer, $router, $twig, $parameters);
    }

    /**
     * @param string $templateName
     * @param array  $context
     * @param string $fromEmail
     * @param string $toEmail
     */
    protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
    {
        // Create a new mail message.
        $message = \Swift_Message::newInstance();
        $mailImgDir = __DIR__ . '/../Resources/images';
        $context['company_logo_cid'] = $message->embed(\Swift_Image::fromPath($mailImgDir.'/your_fancy_logo.png'));

        $context = $this->twig->mergeGlobals($context);
        $template = $this->twig->loadTemplate($templateName);
        $subject = $template->renderBlock('subject', $context);
        $textBody = '';
        $htmlBody = $template->render($context);

        $message
            ->setSubject($subject)
            ->setFrom($fromEmail)
            ->setTo($toEmail);

        if (!empty($htmlBody)) {
            $message
                ->setBody($htmlBody, 'text/html')
                ->addPart($textBody, 'text/plain');
        } else {
            $message->setBody($textBody);
        }

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

在您的services.yml中注册此课程:

# Service that extends the default twig mailer
foo_bar.custom_mailer:
    class: Foo\BarBundle\Mailer\CustomUserMailer
    public: false
    arguments:
        - '@mailer'
        - '@router'
        - '@twig'
        - template:
            confirmation: %fos_user.registration.confirmation.template%
            resetting: %fos_user.resetting.email.template%
          from_email:
            confirmation: %fos_user.registration.confirmation.from_email%
            resetting: %fos_user.resetting.email.from_email%

接下来,让FosUserBundle知道它应该使用这个Mailer类,方法是在config.yml文件中添加以下内容:

fos_user:
    service:
        mailer: foo_bar.custom_mailer

假设您已将公司徽标放在src/Foo/BarBundle/Resources/images/your_fancy_logo.png中,您现在可以在邮件模板中引用该图像:

<img width="xxx" height="xxx" border="0" alt="My fancy company logo" src="{{ company_logo_cid }}" />

答案 1 :(得分:0)

这是一个更清洁的解决方案。

  1. 创建新服务:
  2. // AppBundle/Mailers/CustomFOSUserMailer.php
    
    namespace AppBundle\Mailers;
    
    use AppBundle\Services\StoreService;
    use AppBundle\Services\ThemeService;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseType;
    
    /**
     * This class overrides default FOS User Mailer
     * We need this to pass some data from our services to the twig templates:
     * > Logo path
     * > Store Phone number & E-mail address
     */
    class CustomFOSUserMailer extends BaseType
    {
        /** @var ThemeService */
        protected $theme;
    
        /** @var StoreService */
        protected $store;
    
        /** @var ContainerInterface */
        protected $container;
    
        public function __construct(
            ThemeService $theme,
            StoreService $store,
            ContainerInterface $container,
            \Swift_Mailer $mailer,
            UrlGeneratorInterface $router,
            \Twig_Environment $twig,
            array $parameters)
        {
            parent::__construct($mailer, $router, $twig, $parameters);
    
            $this->theme     = $theme;
            $this->store     = $store;
            $this->container = $container;
        }
    
        /**
         * Overriding sendMessage of the parent class, so we can render our variables
         *
         * @param string $templateName
         * @param array  $context
         * @param string $fromEmail
         * @param string $toEmail
         */
        protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
        {
            $request = $this->container->get('request');
            $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
    
            $context = array_merge($context, [
                'storeLogoUrl'  => $baseurl . $this->theme->logoImage(),
                'storePhone'    => $this->store->getCurrentStore()->getPhone(),
                'storeEmail'    => $this->store->getCurrentStore()->getEmail(),
            ]);
    
            parent::sendMessage($templateName, $context, $fromEmail, $toEmail);
        }
    }
    
    1. 注册服务:
    2. // services.yml
      services:
          app.mailer.custom_fos_user_mailer:
              class: AppBundle\Mailers\CustomFOSUserMailer
              arguments:
                  - @app.theme
                  - @app.store
                  - @service_container
                  - @mailer
                  - @router
                  - @twig
                  -
                      template:
                          confirmation: %fos_user.registration.confirmation.template%
                          resetting: %fos_user.resetting.email.template%
                      from_email:
                          confirmation: %fos_user.registration.confirmation.from_email%
                          resetting: %fos_user.resetting.email.from_email%
      
      1. OVERRIDE FOS DEFAULT MAILER
      2. // config.yml    
        fos_user:
            service:
                mailer: app.mailer.custom_fos_user_mailer
        
        registration:
            confirmation:
                enabled: true
                template: AppBundle:emails/user:confirm.html.twig
        
        1. TWIG示例:
        2. <img src="{{ storeLogoUrl }}" height="50">