DIY-Stories

Send emails from Symfony 5.0 and above

Send emails from Symfony 5.0 and above

Send emails from Symfony 5.0 and above

Symfony's Mailer and Mime components form a powerful system for creating and sending emails.

It allows multi-party message support, Twig integration, inline CSS integration, add attachments and much more.

Installation

Install them with:

composer require symfony / mailer

Setting

Emails are sent via a "provider". By default, you can send emails via SMTP by configuring it in your .env file (the user, pass and port settings are optional but highly recommended).

# .env

MAILER_DSN = smtp: // user: pass@smtp.example.com: port

If you are migrating from Swiftmailer (and the Swiftmailer bundle), be aware that the DSN format is different.

There are other providers than your own SMTP server, you can send emails through a third-party provider. Mailer supports several - install the one you want:

Service Install with the command
Amazon SES composer require symfony / amazon-mailer
Gmail composer require symfony / google-mailer
MailChimp composer require symfony / mailchimp-mailer
Mailgun composer require symfony / mailgun-mailer
Postmark composer require symfony / postmark-mailer
SendGrid composer require symfony / sendgrid-mailer

Each library includes a Symfony Flex setting that will add a sample configuration to your .env file.

For example, suppose you want to use Amazon SES. First, install it:

composer require symfony / amazon-mailer

A line will be added to your .env file that you can uncommment and add the parameters:

###> symfony / amazon-mailer #### MAILER_DSN = ses: // ACCESS_KEY: SECRET_KEY @ default? Region = eu-west-1# MAILER_DSN = ses + smtp: // ACCESS_KEY-eu-1 West region =?

The MAILER_DSN is not a real address but a format that allows you not to have to configure the mailer for each use.

He Amazon SES schema enables the AWS SES provider you just installed, which knows everything about how to deliver messages through AWS SES. The only part to configure in this example is the ACCESS_KEY, the SECRET_KEY as well as the region.

Each provider has different variables that the Mailer uses to configure the service, address, and authentication for delivery. Some also have options that can be configured with query parameters at the end of the MAILER_DSN? like? region = for Amazon SES or Mailgun. Some providers support sending via http, api, or smtp. Symfony chooses the best transport available, but you can force the use of only one.

Check the DSN format for your provider.

Create and send a message

To send an email you must first load the SymfonyComponentMailerMailerInterface and SymfonyComponentMimeEmail libraries

use SymfonyComponentMailerMailerInterface; use SymfonyComponentMimeEmail;
sendmailcontrollerextends AbstractController class {

/**
* @Route ("/ send_email")
*/
public function sendEmail (MailerInterface $mailer)
{
$email = new Email ();
$email-> from ('hello@test.com ')
$email-> to ('you@test.com ')
$email-> subject ('Test with Symfony Mailer')
$email-> text ('Sending test emails with Symfony!')
$email-> html ('See Twig integration for better

HTML integration! ');
$mailer-> send ($email);
}

}

That's all! The message will be sent through the provider you have configured.

Here are some additional methods you can use

-> cc ('cc@example.com ') -> bcc ('bcc@example.com') -> replyTo ('fabien@example.com ') -> priority (Email :: P RIORITY_HIGH)

Add a sender and recipient email address

Methods for providing email addresses (from (), to (), etc.) accept both a character string and an Object of type Address

use SymfonyComponentMimeAddress; $email = (new Email ())

e-mail address as a simple string
-> from ('test@demo.fr ')

email address as object
-> from (new Address ('test@demo.fr '))

set the email address and name as a subject (email clients will display the name)
-> from (new Address ('test@demo.fr ',' My Name '))

set the email address and name as a string
(the format must be: 'Name')
-> from (Address :: fromString ('Name '));

You can add multiple email addresses using the addTo () function:

$email = new Email ();

$email-> addTo ('Test@example.com ');
$email -> -> addTo ('baz@example.com ');
...

You can do the same with the other cc or bcc tu functions as follows:

$email = new Email ();

$email-> cc ('cc1@test.com ',' cc2@test.com ');
$email-> bcc ('cc1@test.com ',' cc2@test.com ');

Message header

A message includes a number of surveys it is possible to customize.

Symphony defaults to all necessary headers but you can also set your own headers if necessary. There are different types of headers (Id header, Mailbox header, Date header, etc.).

Headers define the following ways:

$email = new Email ();

$email-> getHeaders ();
this header tells auto-replicators ("email vacation mode") not to respond
to this message because it is an automated email -> addTextHeader ('X-Auto-Response-Suppress', 'OOF, DR, RN, NRN, AutoReply');

How to add content to your email

It is possible to add text or html content to your email, but it is also possible to add other resources thanks to PHP functions.

HTML rendering can also be formatted with CSS style sheets, as well as with Twig templates.

$email = new Email ();

$email-> text ('Mount plain text');
$email-> html ('My HTML Text
');

To add content from an existing file do the same by retrieving your text with the function fopen the PHP

$email = new Email ();

$email-> text ('/ path / to / emails / user_signup.txt', 'r'));
$email-> html (fopen ('/ path / to / emails / user_signup.html', 'r'));

How to attach a file to your email

It is regularly necessary to add attachments to an email, for this it is enough to use the attachFromPath () function.

To attach the files they will need to be present on the server that will send the email.

$email = new Email ();

$email-> attachFromPath ('/ path / to / documents / terms-of-use.pdf');

Optionally, you can have email clients display a custom name for the file.
$email-> attachFromPath ('/ path / to / documents / privacy.pdf', 'Privacy Policy');

Optionally, you can provide an explicit MIME type (otherwise it is determined automatically).
$email-> attachFromPath ('/ path / to / documents / contract.doc', 'Contract', 'application / msword');

you can also use an absolute URL if your PHP configuration allows you to retrieve URLs using fopen ()
(this is not recommended because your application may or may not work depending on the PHP configuration).
$email-> attachFromPath ('http://example.com/path/to/documents/contract.doc', 'Contract', 'application / msword');

At the same time it was really possible to attach a file using a stream with the attach () method

$email = new Email ();

$email-> attach ('/ path / to / documents / contract.doc', 'r'));

Insert a picture

If you want to display an image within your email you must embed them instead of adding them as an attachment. If you use Twig to generate the content of your email your images are automatically integrated (you will have more details about this in another article).

You must embed the images manually using the following methods embed () or embedFromPath (), from a file or stream.

$email = new Email ();

retrieve image content from a PHP resource
$email-> embed (fopen ('/ path / to / images / logo.png', 'r'), 'logo');

retrieve the contents of the image from an existing file
$email-> embedFromPath ('/ path / to / images / signature.gif', 'footer-signature');

The 2nd optional parameter the 2 methods and the name ("Content-ID" in the MIME standard). This value is later used to reference images in the HTML.

Send email

To send an email we proceeded in 2 steps.

The first is the creation of the email itself by adding the sender, the recipients as well as the content of the message (text and / or attachment).

Then the 2nd step which consists of sending the email using the mailer you will have been previously set up and instantiated.

$mailer-> send ($email);

In a future article we will enter the more advanced functions allowing you to customize the behavior of sending emails, as well as their content.

Translation of the article Source: https: //symfony.com / doc / current / mailer.html

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.