May 7, 2019 Javier Eguiluz

Symfony provides more than 60 decoupled components to solve common needs of web and console applications. New Symfony versions usually introduce new components and Symfony 4.3 will be no exception. In this blog post you'll learn about one of those new components: Mime component.

This component helps you create and manipulate the MIME messages used to send emails and provides utilities related to MIME types. The full MIME standard (Multipurpose Internet Mail Extensions) is a set of standards that define additional capabilities for the original text-based emails (such as rich HTML formatting and file attachments).

The Mime component abstracts all that complexity to provide two ways of creating MIME messages. The first one is a high-level API based on the Symfony\Component\Mime\Email class to quickly create email messages with all the common features:

1 2 3 4 5 6 7 8 9 use Symfony\Component\Mime\Email ; $email = ( new Email ()) -> from ( [email protected]' ) -> to ( [email protected]' ) -> subject ( 'Important Notification' ) -> text ( 'Lorem ipsum...' ) -> html ( '<h1>Lorem ipsum</h1> <p>...</p>' ) ;

The other way to create MIME messages is a low-level API based on the Symfony\Component\Mime\Message class which gives you absolute control over every single part of the email message:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 use Symfony\Component\Mime\Header\Headers ; use Symfony\Component\Mime\Message ; use Symfony\Component\Mime\Part\Multipart\AlternativePart ; use Symfony\Component\Mime\Part\TextPart ; $headers = ( new Headers ()) -> addMailboxListHeader ( 'From' , [ [email protected]' ]) -> addMailboxListHeader ( 'To' , [ [email protected]' ]) -> addTextHeader ( 'Subject' , 'Important Notification' ) ; $textContent = new TextPart ( 'Lorem ipsum...' ); $htmlContent = new TextPart ( '<h1>Lorem ipsum</h1> <p>...</p>' , 'html' ); $body = new AlternativePart ( $textContent , $htmlContent ); $email = new Message ( $headers , $body );

The Mime component provides many other utilities to create email messages:

Flexible definition of email addresses using strings, objects, named addresses, etc.

Image embedding, which is needed when sending complex HTML emails.

File attachments, using physical files and/or PHP resources.