Search code examples
phphtmlzend-framework2html-emailnewsletter

How to create HTML template with images for newsletter in Zend Framework 2


I want to create a HTML template with inline images.

In Module.php I have configuration:

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'mail.transport' => function (ServiceManager $serviceManager) {
                $config = $serviceManager->get('Config');
                $transport = new Smtp();
                $transport->setOptions(new SmtpOptions(
                        array(
                            'name' => 'localhost.localdomain',
                            'host' => '127.0.0.1',
                            'port' => 25,
                        )
                    )
                );
                return $transport;
            },
        ),
    );
}

Function for sending a mail is bellow:

public function SendMail()
    {
        // HTML 
        $this->renderer = $this->getServiceLocator()->get('ViewRenderer');  
        $content = $this->renderer->render('email/tpl/template', null);
        $html = new MimePart($content);  
        $html->type = "text/html";   

        // BODY
        $body = new MimeMessage();  
        $body->setParts(array($html,));

        // INSTANCE MAIL   
        $message = new Message();  
        $message->setBody($body) 
                ->addTo('[email protected]')
                ->addFrom('[email protected]')
                ->setSubject('SUBJECT');

        $transport = $this->getServiceLocator()->get('mail.transport');
        $transport->send($message);
    }

In view/email/tpl/template.phtml:

<h1>Mail Template</h1>  
Some text here<br>
<img src="./public/img/image.jpg"/><br>

But in the mail I don't see any images (or broken links to images), only text.


Solution

  • Try this

    <h1>Mail Template</h1>  
    Some text here<br>
    <img src="<?= $this->url('your-root-route',array('force_canonical'=>true))?>public/img/image.jpg"/><br>
    

    your root route is route to main page ("/")

    force_canonical generate absolute url with http:// etc.