Wednesday 31 October 2012

Zend Framework 2 : Send Html Mail with Simple Template

Here is my experiment with some help from my friend, how to use zend framework 2 mail component to sent mail as html. Even though we don't have any mail server or we just don't want to think of how to set mail server but with this component we could send mail easily. In this section, we will utilize a reliable smtp server like Gmail. Then we just have to have an account on the web mail to use the service for send mail.

Before we move on to the code, make sure that openssl have activated on our php.ini configuration. By doing uncomment extension=php_openssl.dll.

Let's assume that we have a module called Email with structure as below


1. Make a template for mail

In view/email directory, there's a tpl directory contains template.phtml. template.phtml file is used for our template content mail that will be sent. Actually, you can make template mail wherever you want.

template.phtml


Greetings

ini template buat email !!
2. Call Namespace Zend Component
// for email library
use Zend\Mail;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
3. Make action on your Controller to send mail
// setup SMTP options
$options = new Mail\Transport\SmtpOptions(array(
            'name' => 'localhost',
            'host' => 'smtp.gmail.com',
            'port'=> 587,
            'connection_class' => 'login',
            'connection_config' => array(
                'username' => 'put your gmail username ',
                'password' => 'put your gmail password',
                'ssl'=> 'tls',
            ),
));
                 
$this->renderer = $this->getServiceLocator()->get('ViewRenderer');
$content = $this->renderer->render('email/tpl/template', null);

// make a header as html
$html = new MimePart($content);
$html->type = "text/html";
$body = new MimeMessage();
$body->setParts(array($html,));

// instance mail 
$mail = new Mail\Message();
$mail->setBody($body); // will generate our code html from template.phtml
$mail->setFrom('sender email address','Sender Name');
$mail->setTo('some email addressed');
$mail->setSubject('Your Subject');

$transport = new Mail\Transport\Smtp($options);
$transport->send($mail);

Copyright © 2012 Clighter | Powered by Blogger