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’s how you can send emails in Symfony2 by properly splitting your functionality and templates.


1. Mailer parameters

First off, you’re going to need to add some email data into your parameters.yml file that will tell Swift Mailer 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’re going to use SendGrid.

As you can see, we’ve also added three parameters that will help us to send emails in Symfony2: contact email, from email and from name.


2. Send emails in Symfony2 using a MailManager

Having a MailManager is helpful because the code needed to send emails will only reside in a single place. Thus, it will be way easier to maintain. Here’s how you should build the MailManager class:

In the sendEmail function, you can easily define a $template variable which will hold whatever template you need, depending on the type of email. You’ll see the MailManager in action in the 4th and last section of this short tutorial, where you’ll use it to send a contact email.

Oh, and don’t forget to register the service in services.yml:


Related: Symfony2 Facebook and Google Login: The Easy Way


3. Define a simple template

In this section you’ll be building the three main blocks any email should have (subject, html and text) and store them in a template which you’ll extend as needed.


4. A sample email sending action

Now that you have everything set, you can go ahead and build your first mail sending action. As an example, here’s how a contact action should look like. It will send emails to the email address defined in parameters.yml.

Since you’ll be using the contact email body, you will need to build it by extending the template defined at step #3:


And there you have it – 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.

Need help with your next project?

Contact us

Privacy Preference Center