user3065301
user3065301

Reputation: 15

Render mail templete zend framework 2

i'm trying to sent an email with a template in Zend framework 2 applicatio. This is code in my class called "EmailService...".

        $view = new PhpRenderer();
    $resolver = new TemplateMapResolver();
    $resolver->setMap(array(
        'mailTemplate' => __DIR__ . '/../../../mail/' . $template['name'] . '.phtml'
    ));
    $view->setResolver($resolver);
    $viewModel = new ViewModel();
    $viewModel->setTemplate('mailTemplate')
            ->setVariables(
                    (!empty($template['variables']) && is_array($template['variables'])) ? $template['variables'] : array()
    );

    $this->_message->addFrom($this->_emailConfig['sender']['address'], $this->_emailConfig['sender']['name'])
            ->addTo($user['email'], $user['login'])
            ->setSubject($subject)
            ->setBody($view->render($viewModel))
            ->setEncoding('UTF-8');

Everything work fine but in this templete file I have to create a link to an action (I have specify route for this). But here is a problem. Becouse when I'm trying to use

<?php echo $this->url('auth') ; ?>

I've got "No RouteStackInterface instance provided" error.

If I use:

<?php echo $this->serverUrl(true); ?>

everything work fine... Any clue?

Upvotes: 0

Views: 201

Answers (2)

Ujjwal Ojha
Ujjwal Ojha

Reputation: 1360

There are a lot of modules which make things easy when sending html mails. You can search them here.

My personal favourite is MtMail. You can easily use templates and layouts. You can easily set default headers(From, Reply-To etc.). You can use this Template Manager feature to better organize e-mail templates in object-oriented manner.

MtMail Usage:

$mailService = $this->getServiceLocator()->get('MtMail\Service\Mail');

$headers = array(
    'to' => '[email protected]',
    'from' => '[email protected]',
);
$variables = array(
    'userName' => 'John Doe',
);
$message = $mailService->compose($headers, 'application/mail/welcome.phtml', $variables);

$mailService->send($message);

Upvotes: 0

AlexP
AlexP

Reputation: 9857

You shouldn't need to create a new instance of the PhpRenderer; you can just reuse the already created one.

$renderer = $this->serviceManager->get('viewrenderer');

$variables = is_array($template['variables']) ? $template['variables'] : array();
$viewModel = new ViewModel($variables);
$viewModel->setTemplate('mailTemplate');

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

In order to follow good DI practice, inject the PhpRenderer into the email service's __construct (rather than the service manager).

Also, the template path can be added in the normal module.config.php

return array(
    'view_manager' => array(
        'template_map' => array(
            'mailTemplate' => __DIR__ . '/../view/foo/bar.phtml',
        ),
    ),
);

Upvotes: 1

Related Questions