Join us
@sofiatarhonska ・ Nov 28,2022 ・ 7 min read ・ 1436 views ・ Originally posted on mailtrap.io
Symfony is another popular PHP framework and a great toolset for web development. Initially, its mailer feature was based on the Swift Mailer library, also widely used for sending emails from PHP applications.
In the Symfony 4.3 release, the new Mailer component was introduced along with the Mime component. This way, Symfony now has an internal email sending system with a wide set of options:
The Mailer component was added to the 4.3 release as an experiment. It has proved successful, and has been constantly improved and updated. In this post, we use Symfony 5.1.
If you would like to master sending messages with Swift Mailer, then follow our Sending emails with Swift Mailer guide.
We assume that you already work with Symfony and are acquainted with its main components and principles.
In Symfony, message creation and sending can be done with the help of two components: Mailer and Mime. Let’s start by installing them both:
Similar to Swift Mailer, the next step is creating a Transport – defining the method of delivering your messages. SMTP is the easiest and most preferable option. And as usual, we will be running our experiments with Mailtrap, an online tool for email testing in pre-production environments. It will keep our test emails safe by catching and displaying them in virtual inboxes. To start, you can create a free account in just three clicks.
Go to your inbox in Mailtrap: you will need to copy your username and password and paste them to the .env file in your Symfony project as follows:
Note: in Swift Mailer the DSN format differs.
Mailer has libraries for such popular email sending providers as Gmail, Sendgrid, Amazon SES, and others. We will get back to them at the end of this post, as soon as we successfully complete our email testing. Then, we will be ready to send emails to the real inboxes.
In Symfony Mailer, email is a data object. To create a message, we will need to autowire the mailer with the MailerInterface
, specify components we are going to use, and create an Email
object. To send an email, go to “http://<your-app-url>/email” (in development, you use “http://127.0.0.1:8000/email”). The route accessible from web is created with the help of @Route
:
Mailer is straightforward and gives you flexibility and options for experiments. You can set email addresses in several ways as both strings and addresses are supported.
To set from()
address you can use either:
Use the same principles to add recipients. Cc, Bcc, ReplyTo, and multiple addresses are available to use:
For more details and alternatives, refer to the corresponding section in the Symfony Mailer documentation.
Symfony creators promote the crafting of email content with the help of Twig templates, another Symfony project. Twig is a template engine for PHP and indeed is a great option to use when creating beautiful emails. It can be customized and offers a list of integrations and extensions. For example, you can use it with the Foundation for Emails framework or create your templates with Markdown. Either way, you can use pure HTML. Let’s start with HTML and then explore Twig’s advanced options.
Add the HTML part directly to the email object (and don’t forget to include the text part, as well):
In Symfony Mailer, you have two main options: direct embedding with embed
argument or CID attachment. (Refer to your image in the message body by setting its Content-ID and using a standard HTML tag.)
If you have used Swift Mailer before, you will notice that embedding images looks pretty similar:
The way you can attach files to your email is very similar to embedding images.
Here, you have the attachFromPath()
method to include files hosted locally or from an external link, as well as attach()
, for reading files from a stream:
Let’s get back to Twig. It’s integrated with the Mime component, which offers you a wide set of options, including CSS inlining and direct integration with HTML/CSS frameworks.
We won’t dive into Twig templating here – just review its capabilities and give an example of rendering a Twig template in Symfony. For more details on creating email templates with Twig, refer to the Symfony documentation: Twig section and Templates section.
Once you have created your template and saved it as a .twig file, instruct the Mime component to render email content from that file. Use the TemplatedEmail
class for this purpose:
The current Twig templates are special because they offer support for other frameworks, which you can install as extensions:
MarkdownExtension
for MarkdownInkyExtension
for Foundation for Emails (earlier it was called Inky)CssInlinerExtension
for CSS inliningAbove, we have examined all main Symfony Mailer functions and capabilities. Let’s build the whole message and test if everything works as intended with Mailtrap. We have already set the MAILER_DSN
value in the .env file. To send a message, we need to use the Mailer
class.
In this example we are including both HTML and plain text parts, adding a PDF file, and embedding an image:
In a few moments, we can check the message in the Mailtrap virtual inbox:
Now, after successful testing, it’s time to review the options for sending real emails from the production.
It is very easy to specify an external SMTP server to send your emails from a Symfony app. With the Mailer component, this task becomes even easier: there is built-in support for the popular ESPs. It means that you should install an appropriate component and then specify a corresponding transport (it can be used from the DSN as well) as follows:
Service | Installation | SMTP credentials |
Amazon SES | composer require symfony/amazon-mailer | smtp://ACCESS_KEY:SECRET_KEY@ses |
Gmail | composer require symfony/google-mailer | smtp://USERNAME:PASSWORD@gmail |
MailChimp | composer require symfony/mailchimp-mailer | smtp://USERNAME:PASSWORD@mandrill |
Mailgun | composer require symfony/mailgun-mailer | smtp://USERNAME:PASSWORD@mailgun |
Postmark | composer require symfony/postmark-mailer | smtp://ID:ID@postmark |
SendGrid | composer require symfony/sendgrid-mailer | smtp://apikey:KEY@sendgrid |
It is also possible to specify several sending providers: a main provider and alternatives. For more detailed information and code samples, refer to the Multiple Email Transports section of the Symfony documentation.
In a similar way, you can configure sending via Mailtrap Email API.
Besides catching and fixing sending issues, our Email API gives developers control over their email deliverability via actionable analytics features.
If you decide to integrate your PHP-based project with our Email API, the setup process is straightforward, once your domain name is set up:
Select SMTP if you want to take that route and copy the below credentials to your project:
Host: send.smtp.mailtrap.io
Port: 587 (recommended), 2525 or 25
Username: api
Password: <YOUR_API_TOKEN>
Auth: PLAIN, LOGIN
STARTTLS: Required
That’s it, you’re all set to send emails. Thanks to the scalable cloud-based architecture, your app can effortlessly send up to ~10,000 emails/second with the Email API.
The new Symfony Mailer is more flexible than Swift Mailer, and provides a wider set of options. It has a modern look and is regularly updated. The list of supported integrations with both templating languages and email sending providers, along with security options, make it worth trying.
But you also have the option to send emails on production with Mailtrap Email API. It takes less than 5 minutes to verify your domain. And you get the SMTP credentials to get you started.
For more in-depth learning of Symfony Mailer, you can take the Symfony Mailer: Love Sending Emails Again course on SymfonyCasts. If you don’t have a subscription there, access is available for $12.
Thank you for taking your time to read our guide! You can find the original version here:https://mailtrap.io/blog/send-emails-in-symfony/
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.