Green Acorn

Blog

Symfony2 Email Helper

In this tutorial I am going to show you how to set up a basic helper class using the Symfony2 PHP framework. By default, Symfony2 doesn’t have a Helper directory in the bundle structure; however, this doesn’t stop us from making one by using Symfony’s built in service container.

First step is to create a bundle. You can do this manually or use the command line to generate a bundle by typing the below and following the instructions:

php app/console generate:bundle

Now you have a newly generated bundle, create a new php file /src/ Greenacorn/ TestBundle/ Helper/ EmailHelper.php and copy and paste the following php code.

<?php

/**
 * Test Helper
 *
 * @package Test
 * @version 0.1
 * @copyright Copyright 2013 (C) Greenacorn Web. - All Rights Reserved
 */

namespace Greenacorn\TestBundle\Helper;

class EmailHelper
{
    /**
     * admin email address
     */
    const EMAIL_FROM = 'example@mydomain.com';

    /**
     * service container
     *
     * @var object
     */
    protected $service;

    /**
     * init service
     *
     * @param object $service
     * @return $this
     */
    public function __construct($service) {
        $this->service = $service;

        return $this;
    }

    /**
     * Send email
     *
     * @param string $to
     * @param twig $view
     * @param string $subject
     */
    public function sendEmail($to, $view, $subject = 'Email from website')
    {
        if ($to) {
            $message = \Swift_Message::newInstance()->setContentType('text/html')
                    ->setSubject($subject)
                    ->setFrom(self::EMAIL_FROM)
                    ->setTo($to)
                    ->setBody($view);

            $this->service->get('mailer')->send($message);
        }
    }

}

Next, we need to tell Symfony’s service container about the new helper class. To do this, simply add the following to: /src/ Greenacorn/ TestBundle/ Resources/ config/ services.yml.

  ## Helpers
  greenacorn.helper.email:
    class: Greenacorn\TestBundle\Helper\EmailHelper
    arguments:
        service: "@service_container"

Now we need to create a html email template that gets rendered when sending the email. We do this by creating a twig template in: /src/ Greenacorn/ TestBundle/ Resources/ views/ Html/ email.html.twig.

Below is a basic HTML email template.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   </head>
   <body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
      <div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
         <table cellspacing="0" cellpadding="0" border="0" width="100%">
            <tr>
               <td align="center" valign="top" style="padding:20px 0 20px 0">
                  <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                     <tr>
                        <th>Email From Website</th>
                     </tr>
                     <tr>
                        <td valign="top">
                           <p style="font-size:12px; line-height:16px; margin:0;">
                              {{ message }}
                           </p>
                        </td>
                     </tr>
                  </table>
               </td>
            </tr>
         </table>
      </div>
   </body>
</html>

Finally we need to configure Swiftmailer by entering the email hosts SMTP details. You do this in: /app/ config/ config.yml.

# Swiftmailer Configuration
swiftmailer:
    transport: smtp
    host:      smtp.test.com
    username:  test@domain.com
    password:  testpass
    spool:     { type: memory }

How to use

Within a controller class, use the following PHP code. It is here where we will render the email template and pass it to the new sendEmail() helper method. The method will initialise Swiftmailer and set all the relevant properties defined in the class.

$html = $this->renderView('GreenacornTestBundle:Html:email.html.twig', array('message' => 'This is a message'));
$this->get('greenacorn.helper.email')->sendEmail('joe@bloggs.com', $html, 'This is a test subject');

You could go much further to improve this basic helper i.e. have one global email template which gets rendered in the helper; save having to render the view in the controller. However, I have left this out for now as you may want the flexibility to choose a template!

I hope you found this Symfony2 web development tutorial useful!

Author:
Posted in: PHP, Symfony
2 comments on “Symfony2 Email Helper

Leave a Reply

Your email address will not be published. Required fields are marked *

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>