{"id":1828,"date":"2015-12-02T09:14:40","date_gmt":"2015-12-02T09:14:40","guid":{"rendered":"https:\/\/intelligentbee.com\/blog\/?p=1828"},"modified":"2024-11-28T13:50:16","modified_gmt":"2024-11-28T13:50:16","slug":"send-emails-in-symfony2-the-right-way","status":"publish","type":"post","link":"https:\/\/intelligentbee.com\/blog\/send-emails-in-symfony2-the-right-way\/","title":{"rendered":"Send Emails in Symfony2: The Right Way"},"content":{"rendered":"<p>No matter what your app is about, at one you point you will have to send emails in Symfony2. Even though this process might seem straightforward and easy to apply, it can actually get pretty tricky. Here&#8217;s how you can send emails in Symfony2 by properly splitting your functionality and templates.<\/p>\n<p>&nbsp;<\/p>\n<h2>1. Mailer parameters<\/h2>\n<p>First off, you&#8217;re going to need to add some email data into your <code>parameters.yml<\/code> file that will tell <span style=\"color: #ff6600;\"><a style=\"color: #ff6600;\" title=\"Swift Mailer\" href=\"http:\/\/swiftmailer.org\/\" target=\"_blank\" rel=\"noopener\">Swift Mailer<\/a> <\/span>which SMTP server to use. At this point, it would be advised to create an account at an email sending service. For this short tutorial, we&#8217;re going to use <span style=\"color: #ff6600;\"><a style=\"color: #ff6600;\" title=\"SendGrid\" href=\"https:\/\/sendgrid.com\" target=\"_blank\" rel=\"noopener\">SendGrid<\/a>.<\/span><\/p>\n<pre class=\"toolbar:2 marking:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:yaml decode:true \">mailer_transport: smtp\r\nmailer_host: smtp.sendgrid.net\r\nmailer_user: your_sendgrid_username\r\nmailer_password: 'your_sendgrid_password'\r\nmailer_port: 587\r\n\r\ncontact_email: contact@yourapp.com\r\nfrom_email: hello@yourapp.com\r\nfrom_name: YourApp<\/pre>\n<p>As you can see, we&#8217;ve also added three parameters that will help us to send emails in Symfony2: contact email, from email and from name.<\/p>\n<p>&nbsp;<\/p>\n<h3>2. Send emails in Symfony2 using a\u00a0MailManager<\/h3>\n<p>Having a MailManager is helpful because the code needed to send emails will only reside\u00a0in a single place. Thus, it will be way easier to maintain. Here&#8217;s how\u00a0you should build the MailManager class:<\/p>\n<pre class=\"toolbar:2 striped:false marking:false ranges:false nums:false nums-toggle:false whitespace-before:1 whitespace-after:1 lang:php decode:true \">&lt;?php\r\n\r\nnamespace AppBundle\\Lib;\r\n\r\nclass MailManager\r\n{\r\n    protected $mailer;\r\n    protected $twig;\r\n\r\n    public function __construct(\\Swift_Mailer $mailer, \\Twig_Environment $twig)\r\n    {\r\n        $this-&gt;mailer = $mailer;\r\n        $this-&gt;twig = $twig;\r\n    }\r\n\r\n    \/**\r\n     * Send email\r\n     *\r\n     * @param   string   $template      email template\r\n     * @param   mixed    $parameters    custom params for template\r\n     * @param   string   $to            to email address or array of email addresses\r\n     * @param   string   $from          from email address\r\n     * @param   string   $fromName      from name\r\n     *\r\n     * @return  boolean                 send status\r\n     *\/\r\n    public function sendEmail($template, $parameters, $to, $from, $fromName = null)\r\n    {\r\n        $template = $this-&gt;twig-&gt;loadTemplate('AppBundle:Mail:' . $template . '.html.twig');\r\n\r\n        $subject  = $template-&gt;renderBlock('subject', $parameters);\r\n        $bodyHtml = $template-&gt;renderBlock('body_html', $parameters);\r\n        $bodyText = $template-&gt;renderBlock('body_text', $parameters);\r\n\r\n        try {\r\n            $message = \\Swift_Message::newInstance()\r\n                -&gt;setSubject($subject)\r\n                -&gt;setFrom($from, $fromName)\r\n                -&gt;setTo($to)\r\n                -&gt;setBody($bodyHtml, 'text\/html')\r\n                -&gt;addPart($bodyText, 'text\/plain')\r\n            ;\r\n            $response = $this-&gt;mailer-&gt;send($message);\r\n\r\n        } catch (\\Exception $ex) {\r\n            return $ex-&gt;getMessage();\r\n        }\r\n\r\n        return $response;\r\n    }\r\n}<\/pre>\n<p>In the <code>sendEmail<\/code> function, you can easily define a <code>$template<\/code> variable which will hold whatever template you need, depending on the type of email. You&#8217;ll see the <code>MailManager<\/code> in action in the 4th and last section of this short tutorial, where you&#8217;ll use it to send a contact email.<\/p>\n<p>Oh, and don&#8217;t forget to register the service in <code>services.yml<\/code>:<\/p>\n<pre class=\"toolbar:2 toolbar-overlay:false toolbar-hide:false toolbar-delay:false show-title:false striped:false marking:false ranges:false nums:false nums-toggle:false wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:yaml decode:true \">mail_manager:\r\n    class:     AppBundle\\Lib\\MailManager\r\n    arguments: [\"@mailer\", \"@twig\"]<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #ff6600;\"><strong>Related:\u00a0<\/strong><a style=\"color: #ff6600;\" title=\"Symfony2 Facebook and Google Login: The Easy Way\" href=\"https:\/\/intelligentbee.com\/blog\/symfony2-facebook-google-login\/\" target=\"_blank\" rel=\"noopener\">Symfony2 Facebook and Google Login: The Easy Way<\/a><\/span><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"line-height: 1.5;\">3. Define a simple\u00a0template<\/span><\/h3>\n<p>In this section you&#8217;ll be building\u00a0the three main blocks any email should have (subject, html and text) and store them in a template which you&#8217;ll\u00a0extend as needed.<\/p>\n<pre class=\"toolbar:2 toolbar-overlay:false toolbar-hide:false toolbar-delay:false show-title:false striped:false marking:false ranges:false nums:false nums-toggle:false wrap:true wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:xhtml decode:true\">{# src\/AppBundle\/Mail\/template.html.twig #}\r\n\r\n{% block subject %}\r\n    default subject\r\n{% endblock %}\r\n\r\n{% block body_text %}\r\n    default text    \r\n{% endblock %}\r\n\r\n{% block body_html %}\r\n    &lt;p&gt;default body&lt;\/p&gt;\r\n{% endblock %}<\/pre>\n<p>&nbsp;<\/p>\n<h3>4. A sample email sending action<\/h3>\n<p>Now that you have everything set, you can go ahead and build your first mail sending action. As an example, here&#8217;s how a contact action should look like. It\u00a0will send emails to the email address defined in <code>parameters.yml<\/code>.<\/p>\n<pre class=\"toolbar:2 toolbar-overlay:false toolbar-hide:false toolbar-delay:false show-title:false striped:false marking:false ranges:false nums:false nums-toggle:false wrap:true wrap-toggle:false whitespace-before:1 whitespace-after:1 lang:php decode:true\">public function contactAction(Request $request)\r\n    {\r\n        $form = $this-&gt;createForm(new ContactType());\r\n\r\n        $form-&gt;handleRequest($request);\r\n\r\n        \/\/this is where we define which template to use\r\n        $template = 'contact';\r\n\r\n        if($form-&gt;isValid()){\r\n            \/\/Get data from the submitted form\r\n            $data = $form-&gt;getData();\r\n            $mail_params = array(\r\n                'firstName' =&gt; $data[\"firstName\"],\r\n                'lastName'  =&gt; $data[\"lastName\"],\r\n                'message'   =&gt; $data[\"message\"],\r\n                'phoneNumber' =&gt; $data[\"phoneNumber\"],\r\n                'email'     =&gt; $data[\"email\"]\r\n            );\r\n\r\n            \/\/grab the addresses defined in parameters.yml\r\n            $to = $this-&gt;container-&gt;getParameter('contact_email');\r\n            $from =  $this-&gt;container-&gt;getParameter('from_email');\r\n            $fromName = $this-&gt;container-&gt;getParameter('from_name');\r\n\r\n            \/\/use the MailManager service to send emails\r\n            $message = $this-&gt;container-&gt;get('mail_manager');\r\n            $message-&gt;sendEmail($template, $mail_params, $to, $from, $fromName);\r\n\r\n            return $this-&gt;redirectToRoute('contact');\r\n        }\r\n\r\n        return $this-&gt;render('AppBundle:StaticPages:contact.html.twig',array(\r\n            'form' =&gt; $form-&gt;createView()\r\n        ));\r\n    }<\/pre>\n<p>Since you&#8217;ll be using the <code>contact<\/code>\u00a0email body, you will need to build it by extending the template defined at step #3:<\/p>\n<pre class=\"toolbar:2 striped:false marking:false ranges:false nums:false nums-toggle:false whitespace-before:1 whitespace-after:1 lang:xhtml decode:true \">{% extends \"AppBundle:Mail:template.html.twig\" %}\r\n\r\n{% block subject %}\r\n    YourApp Contact Message\r\n{% endblock %}\r\n\r\n{% block body_text %}\r\n    {% autoescape false %}\r\n        Name: {{ firstName }} {{ lastName }}\r\n        Message: {{ message }}\r\n        Phone Number: {{ phoneNumber }}\r\n        Email address: {{ email }}\r\n    {% endautoescape %}\r\n{% endblock %}\r\n\r\n{% block body_html %}\r\n    {% autoescape false %}\r\n        &lt;p&gt;Name: {{ firstName }} {{ lastName }}&lt;\/p&gt;\r\n        &lt;p&gt;Message: {{ message }}&lt;\/p&gt;\r\n        &lt;p&gt;Phone Number: {{ phoneNumber }}&lt;\/p&gt;\r\n        &lt;p&gt;Email address: {{ email }}&lt;\/p&gt;\r\n    {% endautoescape %}\r\n{% endblock %}<\/pre>\n<p>&nbsp;<\/p>\n<p>And there you have it &#8211; an easy way to build and maintain your emails. If you know of any other easier system used to send emails in Symfony2, please let me know in the comment section below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>No matter what your app is about, at one you point you will have to send emails in Symfony2. Even [&hellip;]<\/p>\n","protected":false},"author":28,"featured_media":1857,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[82],"tags":[127,194,238],"yst_prominent_words":[302,545,546,553,593,1029,1356,1427,1948],"post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1828"}],"collection":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/users\/28"}],"replies":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/comments?post=1828"}],"version-history":[{"count":2,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1828\/revisions"}],"predecessor-version":[{"id":133326,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/posts\/1828\/revisions\/133326"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media\/1857"}],"wp:attachment":[{"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/media?parent=1828"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/categories?post=1828"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/tags?post=1828"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/intelligentbee.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=1828"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}