Question

I'm using the next code inside a method to send one kind of email:

    $message = \Swift_Message::newInstance('smtp.gmail.com', 465, 'ssl')
        ->setSubject($this->translator->trans("Invitación a la comunidad %community%", array(
            '%community%' => $community->getNiceName()
        )))
        ->setFrom('manolez@gmail.com', 'contact') // TODO DRY
        ->setTo($email)
        ->setReplyTo($inviter->getEmail(), $inviter->getFullName())
        ->setContentType('text/html')
        ->setBody($this->templating->render(
            'ProInvitationsBundle:Invitations:inviteEmail.html.twig',
            array('community' => $community, 'inviter' => $inviter)));

I want to embed an image to the body, so I could do:

    $message = \Swift_Message::newInstance('smtp.gmail.com', 465, 'ssl')
        ->setSubject($this->translator->trans("Invitación a la comunidad %community%", array(
            '%community%' => $community->getNiceName()
        )))
        ->setFrom('manolez@gmail.com', 'contact') // TODO DRY
        ->setTo($email)
        ->setReplyTo($inviter->getEmail(), $inviter->getFullName())
        ->setContentType('text/html')
        ->setBody('<html><head></head><body>Here is an image <img src="' .
             $message->embed(Swift_Image::fromPath('http://site.tld/logo.png')) .
         '" alt="Image" />' .
         '  Rest of message' .
         ' </body></html>');

but in this way, the $message is not defined yet, and also I can't render my template. Any idea of how to achieve to embed an image to my defined template?

Was it helpful?

Solution

Try this:

$message = \Swift_Message::newInstance();
$imgUrl = $message->embed(Swift_Image::fromPath('http://site.tld/logo.png'));
$message->setSubject($this->translator->trans("Invitación a la comunidad %community%", array(
        '%community%' => $community->getNiceName()
    )))
    ->setFrom('manolez@gmail.com', 'redConvive') // TODO DRY
    ->setTo($email)
    ->setReplyTo($inviter->getEmail(), $inviter->getFullName())
    ->setBody($this->templating->render(
        'ProInvitationsBundle:Invitations:inviteEmail.html.twig',
        array('community' => $community, 'inviter' => $inviter, 'url'=>$imgUrl)
    ), 'text/html');

for more detailed info on how to use SwiftMailer, it's always good to Read the Documentation

UPDATE

To include the image in a twig template, you use it like any other twig variable:

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

OTHER TIPS

I just wanted to add to Sehael's answer.

This is how you generate the full URL. You can get the base URL using the request service:

$request = $this->container->get('request');
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();

$url = $baseurl . '/img/logo.png';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top