1
votes

Trying to build a responsive email template in a Twig file. Using Swiftmailer within a Symfony application to send the emails. Two issues I am having so far is the images only show when I view the email on my localhost not when the email is viewed in Gmail, Inbox or Yahoo!

Linking the images using an absolute path (currently). Also, tried a relative path with the same result.

<img src="{{ absolute_url(asset('bundles/coreecommerce/images/logo.png')) }}">

Problem #2 is include stylesheets. I have some media queries in a stylesheet I am trying to include within a head tag like this.

  {% block stylesheets %}
    <link href="{{ asset('bundles/coreecommerce/css/email.css') }}" rel="stylesheet" />
  {% endblock %}

I'm doing something wrong here. Just not sure what? Can you include stylesheets, inline styles for a responsive email in Twig?

Thanks for any help.

1
Both Gmail, Inbox, and Yahoo will all use external asset blocking for emails to prevent view detection from uniquely generated URLs (e.g. http://www.malicious.com/spamlink.php?email=bob@hackme.com.) The way around this is base64 encoding your images into the email, and using inline CSS.sjagr
And by inline CSS, I mean style attributes, not style tags.sjagr
Would that look like this? <img src="data:image/png;base64,{{ absolute_url(asset('bundles/coreecommerce/images/logo.png')) }}">Brent
Like what? If you're talking about what you've written in your question, no. Not at all.sjagr

1 Answers

0
votes

To inline images in your html mails you should take a look at this section of the documentation.

To show you the example with twig, you can start with something like this:

<?php

$message = \Swift_Message::newInstance();

$fileToEmbed = 'a path to image file';

$templateParams = [
    'fileToEmbed' => $message->embed(\Swift_Image::fromPath($fileToEmbed)),
];

// then compose the mail like this
$message
    // set subject etc...
    ->setBody($this->twigTemplating->render('yourMailTemplate.html.twig', $templateParams), 'text/html')
;

And then in you twig template you just create a IMG tag with template variable:

<img src="{{ fileToEmbed }}">

So TL;DR you just need that $message->embed(\Swift_Image::fromPath($fileToEmbed)) return value to be passed to your mailing template and use it as src attribute.


To locate the image file within your bundle you can use Kernel::locateResource method like this (assuming that your logo.png is located in CoreEcommerceBundle/Resources/public/images/ directory):

$fileToEmbed = $this->kernel->locateResource('@CoreEcommerceBundle/Resources/public/images/logo.png');