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

FOS UserBundle how to add image to registration email twig

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

我已完成覆盖默认模板并启用 swift 邮件程序。

到目前为止尝试过:

<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!" />

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

提前致谢

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

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

首先,在您的自定义用户包中创建一个 class(当您有 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 中注册这个 class:

# 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%

接下来,通过将以下内容放入您的 config.yml 文件,让 FosUserBundle 知道它应该使用此 Mailer class:

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. 创建新服务:
// 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. 注册服务:
// 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. 覆盖 FOS 默认邮件程序
// 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 示例:
<img src="{{ storeLogoUrl }}" height="50">