Platform: Zend Framework 2
Objective: from a controller send an email using Zend/View for the email body

In every day practice Zend\View is called inside a controller action, some variables are passed through the constructor, a template is set and then the view model is returned. The rendering of the view is taken care of. But what if you do not want to render the view immediately but want to capture the output? The code snippet below demonstrates how to use the view model for generating an email body:

$mail = new Zend\Mail\Message;

$bodyPart = new Zend\Mime\Message;

$viewModel = new ViewModel();

$viewModel->setVariable('param', array());


$renderer = new \Zend\View\Renderer\PhpRenderer;

$resolver = new \Zend\View\Resolver\AggregateResolver();

$map = new \Zend\View\Resolver\TemplateMapResolver(array(
'send/mail' => __DIR__ . '/../../../view/application/send/mail.phtml',


$mailBody = $renderer->render($viewModel);

$htmlPart = new Zend\Mime\Part($mailBody);
$htmlPart->type = 'text/plain';



$mail->setFrom($from, $fromName);



$transport = new \Zend\Mail\Transport\Sendmail();

Basically a renderer is required to capture the view which in turn requires a resolver to the find the template file. That is where the map comes in. This last bit is counter-intuitive because a view manager configuration has already been set in the module config.

A simple


is just not going to work.

Of course the are several renderers and several resolvers to choose from, adding to the challenge.

ZF1 practice

In ZF1 a view script can also be rendered to a variable:

$text = $this->view->render('account/view.phtml');

Check if the correct script paths exist with $this->view->getScriptPaths()