asset()
will create an url to the image on your website. This will make a lot a spam filters ring the alarm and most email clients just block the image. Luckily you can embed images using the Swiftmailer.
I assume that you have already configured custom email templates as explained in Sending HTML mails.
First, create a class in your custom user bundle (when you have overwritten the FosUserBundle) or otherwise somewhere else, e.g. 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);
}
}
And register this class in your 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%
Next, let the FosUserBundle know that it should use this Mailer class by putting the following in your config.yml file:
fos_user:
service:
mailer: foo_bar.custom_mailer
Assuming that you have put your company logo in src/Foo/BarBundle/Resources/images/your_fancy_logo.png
you can now reference the image in your mail templates:
<img width="xxx" height="xxx" border="0" alt="My fancy company logo" src="{{ company_logo_cid }}" />