The Mime component provides tools to create and manipulate MIME messages. In Symfony 7.2, we introduced new features to improve it.
Custom MIME Encoders
The MIME standard was created to extend the original format of email messages to
support text in character sets other than ASCII, as well as attachments of any type.
In Symfony's Mime component, this is possible in part thanks to the encoders used
by TextPart
elements. Previously, the encoders were a hardcoded list (quoted-printable
,
base64
, 8bit
).
In Symfony 7.2, TextPart
items allow you to define custom encoders for your specific
needs. For example, if your app uses SOAP Attachments, you'll need to create
a custom encoder like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
use Symfony\Component\Mime\Encoder\ContentEncoderInterface;
class MyEncoder implements ContentEncoderInterface
{
public function encodeByteStream($stream, int $maxLineLength = 0): iterable
{
// ...
}
public function encodeString(string $string, ?string $charset = 'utf-8', int $firstLineOffset = 0, int $maxLineLength = 0): string
{
// ...
}
public function getName(): string
{
return 'my_encoder';
}
}
Now, you can use this encoder in your TextPart
items when creating the MIME message:
1 2 3
// ...
TextPart::addEncoder(new MyEncoder());
$content = new TextPart('...', 'utf-8', 'plain', 'my_encoder');
Unicode Email Addresses Support
Traditionally, email addresses only allowed ASCII characters in both the local part and the domain part. This was inconvenient for a large part of the world's population, so RFC 6531 introduced an extension to the SMTP protocol to support internationalized email addresses.
In Symfony 7.2, we're adding support for Unicode characters in both the local and domain parts of email addresses:
1 2 3 4 5
use Symfony\Component\Mime\Email;
$email = (new Email())
->from('jânë.dœ@ëxãmplę.com')
// ...
You don't need to change anything in your application to use this feature.
If the origin SMTP server (the one where the Symfony application is hosted) doesn't
support Unicode email addresses, you'll see an InvalidArgumentException
with
an error message explaining the issue.
Nice improvements 👏.
I'm just curious that adding content encoder interface requires a method
getName()
and that a name is also needed when callingTextPart::addEncoder
. Is that really intended?I also found it strange to use aliases when everywhere else we are now encouraged to use FQCN directly 😁
About requiring to pass the encoder name, we changed that in https://github.com/symfony/symfony/pull/58764
We also updated the blog post and now the
addEncoder()
method only requires passing the encoder object.@Loick Piera the name of the content encoder actually appears as part of the mime message, in the
Content-Encoding
header. It is not just an internal alias of the Symfony project. So using the FQCN is not an option hereAlright, thanks @Javier for the changes and @Christophe for the explanation. It's all good then 🎉
Small error here: